How to Create a Simple Address Book in C#

In today’s tutorial, we are going to make a simple address book in C#. We will see how to create lists and arrays and use them in a real world application such as this simple address book. I am also going to be trying something new with this tutorial where I am asking you to implement what is missing.

Requirements

Difficulty: Easy

We want to create an address book that will hold a first and last name of each person. It will hold their phone number and also up to 2 addresses for each person. We want the user to be able to add more people to this address book and be able to list them out. If for some reason, the user wants to remove a person from the address book then we want to be able to do so.

One last thing, this address book will not persist data. This means that once the application closes the user will lose the information stored in the address book and the address book will always be empty when the application starts. I hope to add that functionality at a later date when we discuss working with files or databases.

Let’s Get Started

To get started, we first need to create an empty C# console application in Visual Studio. For more information on how to do this, check out my how-to guide here.

The Person Class

The first thing we want to do after creating a blank console application is to add a person class under the Program class. This person class will be the framework for each person that will be stored in the address book. See the code below to see how we set this up.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string PhoneNumber { get; set; }
    public string[] Addresses { get; set; }
}

In the above code, you will see that in our Person class we have a string property for each the first name, last name, and phone number. We also have a string array property to hold the two addresses.

The People List

Now that we have a way to define a person to store in the address book we need somewhere to store all of these people. That is where a list comes into play. Above the Main method, we are going to add a public static list that holds a list of Person objects. See the following code to see how to do this.

public static List<Person> People = new List<Person>();

Above is the line of code we need to add above the Main method that will create an empty list of Person objects that are created from the Person class.

Note: This list will be empty every time the application starts so, therefore, the application will not persist data or in other words, it will not keep the people the user enters into the address book after the application closes.

Adding People

Now that we have a framework to create a person object and a list to hold these people, it is time to add a method to the Program class to add a person to the People list. Check out the code below to see how to do this.

private static void AddPerson()
{
    Person person = new Person();

    Console.Write("Enter First Name: ");
    person.FirstName = Console.ReadLine();

    Console.Write("Enter Last Name: ");
    person.LastName = Console.ReadLine();

    Console.Write("Enter Phone Number: ");
    person.PhoneNumber = Console.ReadLine();

    Console.Write("Enter Address 1: ");
    string[] addresses = new string[2];
    addresses[0] = Console.ReadLine();
    Console.Write("Enter Address 2 (Optional): ");
    addresses[1] = Console.ReadLine();
    person.Addresses = addresses;
      
    People.Add(person);
}

In the above code, we are creating a method below the Main called “AddPerson”. Inside this method, we are first creating a new Person object called “person” from the Person class we created earlier. We are then getting the first name, last name, and phone number from the user and assigning it to the corresponding properties in the person object.

We are then getting address 1 from the user and assigning it to the first position in the addresses string array. Similarly, we are getting the optional address 1 from the user and assigning it to the second position in the array. If the user leaves this blank then we will just store an empty string in the array.

Listing out the People

Once we have people in our address book we want to be able to list out the people in the address book to the screen. We will create two new methods to do this.

Print Person Method

First, let’s create a method called “PrintPerson” below the “AddPerson” method. This method will take a Person object as a parameter which we will call “person”. Inside this method, we will write to the console all of the properties associated with that person. Last we will write to the console a bunch of dashes to put a line below the person’s details (this is just a visual thing). Check out the code below for how we create this method

private static void PrintPerson(Person person)
{
    Console.WriteLine("First Name: " + person.FirstName);
    Console.WriteLine("Last Name: " + person.LastName);
    Console.WriteLine("Phone Number: " + person.PhoneNumber);
    Console.WriteLine("Address 1: " + person.Addresses[0]);
    Console.WriteLine("Address 2: " + person.Addresses[1]);
    Console.WriteLine("-------------------------------------------");
}

List People Method

After the PrintPerson method let’s create a method called “ListPeople”. Inside this method, we are going to first check to see if there are any people in the People list. If not, we will write to the console and tell the user the address book is empty and to press any key to continue. We will use the Console.ReadKey() method to force the application to wait for the user to press a key.

Once the user presses a key on the keyboard, the application will hit a return statement that will jump out of this method. We do this because we do not want to execute the rest of the code in this method because there is nothing else to do, the address book is empty.

Below the if statement we are going to tell the user “Here are the current people in your address book:” Then we have a foreach loop that will iterate over each person in the people list. For each person in the for each loop we will call the “PrintPerson” method, passing the person object. After the foreach loop, we will tell the user to press any key to continue and use the Console.ReadKey like before. See the code below for how the ListPeople method should look.

private static void ListPeople()
{
    if (People.Count == 0)
    {
        Console.WriteLine("Your address book is empty. Press any key to continue.");
        Console.ReadKey();
        return;
    }
    Console.WriteLine("Here are the current people in your address book:\n");
    foreach (var person in People)
    {
        PrintPerson(person);
    }
    Console.WriteLine("\nPress any key to continue.");
    Console.ReadKey();
}

Removing People

Now that we have a way to add people to our address book and a way to list out the people in the address book, it is time to add the functionality to remove a person from our address book.

First, we want to create a new method like before and name it “RemovePerson”. Inside this method, we want to collect the first name of the person we want to remove from our address book. Then we want to use LINQ to query the list for the first person with the same first name as the first name the user entered. See below.

Console.WriteLine("Enter the first name of the person you would like to remove.");
string firstName = Console.ReadLine();
Person person = People.FirstOrDefault(x => x.FirstName.ToLower() == firstName.ToLower());

In the above code, you will see we are using LINQ to check the person list for

the same first name as the user entered. Basically what the LINQ statement above does is look for at each person in the person list and then check to see if the lowercase of that person’s first name is the same as the lowercase of the user’s input first name. If so, then return that person object and assign it to the variable “person”.

By using the “FirstOrDefault” method instead of the “First” method we are preventing errors if the person is not found. If there is no person with the same first name then the LINQ statement return “null”. Therefore the next thing we want to do is check to see if person is equal to null. If so tell the user that person could not be found and to press any key to continue. Like before we will use the Console.ReadKey method and then the return statement. See code below.

if (person == null)
{
    Console.WriteLine("That person could not be found. Press any key to continue");
    Console.ReadKey();
    return;
}

If the person is found, we want to confirm with the user that they really do want to remove this person from their address book. We will do this with the code below.

Console.WriteLine("Are you sure you want to remove this person from your address book? (Y/N)");
PrintPerson(person);

if (Console.ReadKey().Key == ConsoleKey.Y)
{
    People.Remove(person);
    Console.WriteLine("Person removed. Press any key to continue.");
    Console.ReadKey();
}

In the above code, we are asking the user if they are sure they want to remove this person from their address book. ‘Y’ for yes and ’N’. We are then printing the person’s details to the screen using the PrintPerson method from before.

If the user presses the ‘y’ key then we are calling the Remove method on the people list and passing the person we want to remove. This will remove the person from the people list thus removing them from the address book. We then tell the user the person has been removed and to press any key to continue.

One last thing, this way of selecting the first user by the first name is a bad way of doing this. What if we have 2 people with the same first name? I am leaving this program like this and am challenging you to find and implement a better way of removing a user. Post your code below in the comments and let me know what you did.

Tying it all together

We now have all of the methods we need to have a fully functioning address book. But if we run the application nothing actually happens. This is because we do not have any code in our Main method. It is time to change that.

In the Main method, we are going to create a string variable called “command” and assign it to an empty string. Then we are going to create a while loop that will loop when command is not equal to “exit”

Inside the while loop, we want to ask the user to enter a command and then assign that command in its lower case form to the command variable. Next, we want to add a switch statement that will switch on the command variable.

If the command is “add” then we want to call the AddPerson method and then break. If the command is “remove” then we want to call the RemovePerson method. Last, if the command is “list” we want to call the ListPeople method. See the code below.

string command = "";
while (command != "exit")
{
    Console.Clear();
    Console.WriteLine("Please enter a command: ");
    command = Console.ReadLine().ToLower();
     switch (command)
    {
        case "add":
            AddPerson();
            break;
        case "remove":
            RemovePerson();
            break;
        case "list":
            ListPeople();
            break;
    }
}

Above you will find the code that should be in the Main method.

What’s Missing

In this application, a few things are missing that I would like for you to try to implement yourself. When you think you have it be sure to post your code in the comments section below so everyone can see.

The first thing missing is a better remove method. I mentioned this above so be sure to look at my note above about this.

This application is also missing a search feature which should be easy to implement by using some of the code from the RemovePerson method.

If the user enters a command that does not exist then they are prompted to enter a command. This not good because it does not help the user if they do not know what to commands they have available to them. Try adding a default case to the switch that displays help if the command is invalid.

During this tutorial, we set up places for the user to press any key to continue. This application would be much more clean of we were to clear the console window during parts of this application. Use Console.Clear() to clear the console window.

If you want to see how I implemented these additional features enter your email below and you will instantly receive the project files I used when creating this application.

[thrive_leads id=’1315′]

In this article, we built a simple address book that a user can add, remove, and list out people. We got to work with arrays and lists and see how they work in a real word application. Although the data does not get saved we will be implementing that soon enough.

If you found this tutorial helpful be sure to check out my C# Roadmap.