Let's think this through for a moment
In this project we'll build a simple Contact Book console app that stores and lets you edit contacts (name, phone, email). We'll reuse the class, object, property, and constructor concepts from the basics chapter to learn how to model a real-world data structure. In Part 1, we'll start by writing the foundation: a Contact class, and a ContactManager class that stores contacts in a List. Get this structure solid, and adding more features in later parts will be a breeze. We'll also handle user input with Console.ReadLine() and build out the basic Add Contact feature.
Let's actually build it
Create a new Console App project, then write a Contact class in Contact.cs with Name, Phone, and Email properties. In the ContactManager class, add a List<Contact> field along with an AddContact() method and a ShowAll() method. In Main(), build a simple menu loop (while loop): when the user picks "1. Add Contact", read the name/phone/email with Console.ReadLine() and call AddContact(); when they pick "2. Show All", call ShowAll() to print the contacts list to the console. Add a condition for "0. Exit" so the loop can end.
Code example
class Contact
{
public string Name { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
class ContactManager
{
private List<Contact> contacts = new List<Contact>();
public void AddContact(Contact c)
{
contacts.Add(c);
Console.WriteLine("Contact added: " + c.Name);
}
public void ShowAll()
{
Console.WriteLine("--- Contact List ---");
foreach (Contact c in contacts)
{
Console.WriteLine($"{c.Name} | {c.Phone} | {c.Email}");
}
}
}
class Program
{
static void Main(string[] args)
{
ContactManager manager = new ContactManager();
bool running = true;
while (running)
{
Console.WriteLine("\n1. Add Contact 2. Show All 0. Exit");
string choice = Console.ReadLine();
if (choice == "1")
{
Console.Write("Name: ");
string name = Console.ReadLine();
Console.Write("Phone: ");
string phone = Console.ReadLine();
Console.Write("Email: ");
string email = Console.ReadLine();
manager.AddContact(new Contact { Name = name, Phone = phone, Email = email });
}
else if (choice == "2")
{
manager.ShowAll();
}
else if (choice == "0")
{
running = false;
}
}
}
}You'll end up with a working console app where a menu appears, you can add contacts, and view them back as a list.5-minute challenge
Add a Category property ("Family", "Work", "Friend") to the Contact class, and show the category in ShowAll() too.
A quick word of caution
Make sure your exit condition in the menu loop is actually correct — get it wrong and you'll end up with an infinite loop.