DEV Community

Kerimova_Manzura
Kerimova_Manzura

Posted on

Building a Simple Contact Book in C#

Managing contacts is a common task, and having a simple, efficient contact book can be extremely useful. In this tutorial, we'll walk through the process of building a basic contact book application in C#. This project covers important concepts such as object-oriented programming, handling collections, and implementing CRUD (Create, Read, Update, Delete) operations.

Step 1: Define the Contact Type Enumeration

The first step is to define an enumeration ContactType to categorize the contacts. This enum allows us to classify contacts into groups such as friends, family, professional, or others.

enum ContactType
{
    friend,
    family,
    professional,
    Other
}
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Contact Struct

Next, we'll create a Contact struct to represent each contact. This struct includes properties for the contact's name, address, phone number, and type. We'll also override the ToString method to provide a readable format for the contact details.


struct Contact
{
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNumber { get; set; }
    public ContactType Type { get; set; }

    public Contact(string name, string address, string phoneNumber, ContactType type)
    {
        Name = name;
        Address = address;
        PhoneNumber = phoneNumber;
        Type = type;
    }

    public override string ToString()
    {
        return $" Name: {Name}\n Address: {Address}\n Phone: {PhoneNumber}\n Type: {Type}";
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Implement the Address Book Class

Now, we'll create an AddressBook class to manage the contacts. This class contains methods to add, edit, delete, and display contacts. It also includes a method to filter contacts by their type.

class AddressBook
{
    private List<Contact> contacts;

    public AddressBook()
    {
        contacts = new List<Contact>();
    }

    public void ContactAdd(Contact contact)
    {
        contacts.Add(contact);
        Console.WriteLine("Contact successfully added.");
    }

    public void ContactEdit(string name, Contact updatedContact)
    {
        for (int i = 0; i < contacts.Count; i++)
        {
            if (contacts[i].Name.Equals(name, StringComparison.OrdinalIgnoreCase))
            {
                contacts[i] = updatedContact;
                Console.WriteLine("Contact updated successfully.");
                return;
            }
        }
        Console.WriteLine("Contact not found.");
    }

    public void ContactOpen(string name)
    {
        var contact = contacts.FirstOrDefault(k => k.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
        if (contact.Equals(default(Contact)))
        {
            Console.WriteLine("Contact not found.");
        }
        else
        {
            contacts.Remove(contact);
            Console.WriteLine("Contact deleted successfully.");
        }
    }

    public void ShowContacts()
    {
        if (contacts.Count == 0)
        {
            Console.WriteLine("No contacts available.");
            return;
        }

        foreach (var contact in contacts)
        {
            Console.WriteLine(contact);
        }
    }

    public void FilterContactsByType(ContactType type)
    {
        var filteredContacts = contacts.Where(k => k.Type == type).ToList();

        if (filteredContacts.Count == 0)
        {
            Console.WriteLine("No contacts found for the selected type.");
        }
        else
        {
            foreach (var contact in filteredContacts)
            {
                Console.WriteLine(contact);
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Create the Main Program

Finally, we'll put everything together in the Main method. This method provides a simple menu for the user to interact with the contact book, allowing them to add, view, edit, delete, and filter contacts.

class Program
{
    static void Main(string[] args)
    {
        AddressBook addressBook = new AddressBook();

        while (true)
        {
            Console.WriteLine("\n1. Add new contact");
            Console.WriteLine("2. Show all contacts");
            Console.WriteLine("3. Edit Contact");
            Console.WriteLine("4. Delete contact");
            Console.WriteLine("5. Filter contacts by type");
            Console.WriteLine("6. Exit");
            Console.Write("Enter your choice (1-6): ");

            string selection = Console.ReadLine()!;

            switch (selection)
            {
                case "1":
                    Console.Write("Enter the name of the contact: ");
                    string name = Console.ReadLine()!;
                    Console.Write("Enter the address of the contact: ");
                    string address = Console.ReadLine()!;
                    Console.Write("Enter the phone number of the contact: ");
                    string phoneNumber = Console.ReadLine()!;

                    Console.WriteLine("Select contact type: (0: Friend, 1: Family, 2: Professional, 3: Other)");
                    int typeSelect = int.Parse(Console.ReadLine()!);
                    ContactType contactType = (ContactType)typeSelect;

                    Contact newContact = new Contact(name, address, phoneNumber, contactType);
                    addressBook.ContactAdd(newContact);
                    break;

                case "2":
                    Console.WriteLine("\nAll contacts:");
                    addressBook.ShowContacts();
                    break;

                case "3":
                    Console.Write("Enter the name of the contact to edit: ");
                    string editableName = Console.ReadLine()!;
                    Console.Write("Enter new name: ");
                    string newName = Console.ReadLine()!;
                    Console.Write("Enter new address: ");
                    string newAddress = Console.ReadLine()!;
                    Console.Write("Enter new phone number: ");
                    string newPhone = Console.ReadLine()!;

                    Console.WriteLine("Select a new contact type: (0: Friend, 1: Family, 2: Professional, 3: Other)");
                    int newTypeSelect = int.Parse(Console.ReadLine()!);
                    ContactType newContactType = (ContactType)newTypeSelect;

                    Contact updatedContact = new Contact(newName, newAddress, newPhone, newContactType);
                    addressBook.ContactEdit(editableName, updatedContact);
                    break;

                case "4":
                    Console.Write("Enter the name of the contact to delete: ");
                    string openName = Console.ReadLine()!;
                    addressBook.ContactOpen(openName);
                    break;

                case "5":
                    Console.WriteLine("Select a contact type to filter: (0: Friend, 1: Family, 2: Professional, 3: Other)");
                    int filterTypeSelect = int.Parse(Console.ReadLine()!);
                    ContactType filterContactType = (ContactType)filterTypeSelect;
                    addressBook.FilterContactsByType(filterContactType);
                    break;

                case "6":
                    Console.WriteLine("Exiting...");
                    return;

                default:
                    Console.WriteLine("Invalid selection! Please select between 1-6.");
                    break;
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

With these steps, you’ve created a basic contact book application in C#. This project is a great way to get familiar with object-oriented programming concepts, handling collections, and implementing basic CRUD operations. From here, you can expand this application by adding more features, such as saving contacts to a file, implementing search functionality, or even creating a graphical user interface (GUI).

Top comments (1)

Collapse
 
chesedgamesonline profile image
ChesedGamesOnline

Awesome! Always want to build something like that! Maybe I could build something like it in Godot?