Create a phone book console application in C#

Getting Started

Run the commanddotnet new console -o PhoneBookConsoleAppon your CLI (Command Line Interface) to create a phone book console application in C#.

Note: Before running the command, make sure .NET SDK (Software development kit) or .NET Runtime is installed on your machine.

.NET SDK or .NET Runtime

The software development kit (SDK) comes with everything you need to build and run .NET programs using command-line tools and any editor (like Visual Studio). Runtime (Windows) The runtime includes each component needed to run .NET programs. The runtime is also part of the SDK.

What are the differences between .NET SDK and .NET Runtime?

The following components make up .NET Core, according to the .NET Core Guide:

  • A .NET runtime, which provides a type system, assembly loading, a garbage collector, native interop and other basic services.

  • A set of framework libraries, which provide primitive data types, app composition types and fundamental utilities.

  • A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK

  • The dotnet app host is used for launching .NET Core apps. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.

The SDK includes everything needed to create a .NET Core application, including the CLI and a compiler.

The runtime is the "virtual machine" that hosts/runs the application and abstracts all the interactions with the base operating system.

Updating the newly generated phone book console app

Add the following code to theProgram.cs class:

using System;

namespace PhoneBookConsoleApp
{
    class Program
    {
        public static void Main(string[]args)
        {
            Console.WriteLine("Hello from the Console PhoneBook app");
            Console.WriteLine("Select operation");
            Console.WriteLine("1 Add contact");
            Console.WriteLine("2 Display contact by number");
            Console.WriteLine("3 View all contacts");
            Console.WriteLine("4 Search for contacts for a given name");
            Console.WriteLine("Press 'x' to exit");
            var userInput = Console.ReadLine();

            var phoneBook = new PhoneBook();

            while(true)
            {
                switch(userInput)
            {
                case "1":
                    Console.WriteLine("Contact name:");
                    var name = Console.ReadLine();

                    Console.WriteLine("Contact number:");
                    var number = Console.ReadLine();

                    var newContact = new Contact(name, number);
                    phoneBook.AddContact(newContact);
                    break;

                case "2":
                Console.WriteLine("Contact number to search");
                    var searchNumber = Console.ReadLine();
                        phoneBook.DisplayContact(searchNumber);
                        break;
                case "3":
                        phoneBook.DisplayAllContact();
                        break;
                case "4":
                Console.WriteLine("Name search phrase");
                    var searchPhrase = Console.ReadLine();

                        phoneBook.DisplayMatchingContacts(searchPhrase);
                        break;
                case "x":
                    return;
                    default:
                    Console.WriteLine("Select valid operation");
                    break;
            }

                Console.WriteLine("Select operation");
                userInput = Console.ReadLine();
            }
        } 
    }
}

Brief explanations of the code sample above:

In the code sample above, our Main() method in the Program.csclass contains some code blocks:

  • The Console.WriteLine() method was used to list some texts to be displayed.

  • userInput variable was assigned to the Console.ReadLine() method to store user input in the variable and also, read through user input.

  • An object PhoneBook() was assigned to the phoneBook variable to add new contact and also display input contacts in the console.

  • Switch statements containing the user-inputted value were nested in the while loop. The while loop was set to true if the conditions in the switch condition is met.

    Note: In order to end the program if no program is anticipated to run, the case "x" in the code was added to the switch statement.

After that, create two new classes named PhoneBook.cs and Contact.cs in the project root directory.

Now, add the following code in the PhoneBook.cs file:

using System;
using System.Text;

namespace PhoneBookConsoleApp
{
    class PhoneBook
    {
        private List<Contact> _contacts { get; set; } = new List<Contact>();
        private void DisplayContactDetails(Contact contact)
        {
            Console.WriteLine($"Contact: {contact.Name}, {contact.Number}");
        }

        private void DisplayContactsDetails(List<Contact> contacts)
        {
            foreach(var contact in _contacts)
            {
                DisplayContactDetails(contact);
            }

        }

        public void AddContact(Contact contact)
        {
            _contacts.Add(contact);
        }

        public void DisplayContact(string number)
        {
            var contact = _contacts.FirstOrDefault(c => c.Number == number);
            if(contact == null)
            {
                Console.WriteLine("Contact not found");
            }
            else
            {
                DisplayContactDetails(contact);
            }
        }

        public void DisplayAllContact()
        {
            DisplayContactsDetails(_contacts);
        }

        public void DisplayMatchingContacts(string searchPhrase)
        {
            var matchingContacts = _contacts.Where(c => c.Name.Contains(searchPhrase)).ToList();
            DisplayContactsDetails(matchingContacts);
        }
    }
}

Brief explanations of the code sample above:

The following methods and fields are part of the code for the PhoneBookclass:

  • We also construct a new contact list object in addition to adding a private List of Contact field and attribute.

  • To display the name and number entered by the user, the DisplayContactDetails() method was created.

  • The second DisplayContactsDetails method is used to list user-input contacts.

  • AddContact method is used to add a contact to the phone book class.

  • DisplayContact, this method is used to display the input contact.

  • DisplayAllContact method is used to list out all phone book contacts.

  • DisplayMatchingContacts this last method is used to search for stored names or numbers in the phone book.

Lastly, add the following code in the Contact.cs file:

using System;
using System.Text;

namespace PhoneBookConsoleApp
{
     class Contact
    {
        public Contact(string name, string number)
    {
        Name = name;
        Number = number;
    }
    public string Name { get; set; }
    public string Number { get; set;}
    }
}

Brief explanations of the code sample above:

The phone book contact constructor and its properties are shown in the aforementioned code sample.

Run the command dotnet run or press Ctrl + F5.

Output

Source Code

Thanks for reading...

Happy Coding!

Did you find this article valuable?

Support FOLASAYO SAMUEL OLAYEMI by becoming a sponsor. Any amount is appreciated!