Welcome! Today, we will explore creating a simple address book application using a C# Dictionary
. This task will help you understand how to manipulate a Dictionary
in C#, focusing on adding, retrieving, and deleting entries. By the end of this lesson, you'll have a solid grasp of these fundamental operations.
In this task, we will implement three methods to manage our address book:
AddContact(string name, string phoneNumber)
: Adds a new contact. Returns false
if the contact already exists; otherwise, it adds the contact and returns true
. In this task, let's assume phone numbers do not change, so it's not allowed to overwrite an existing contact's number.GetContact(string name)
: Retrieves the phone number for a given name
. Returns null
if the contact does not exist.DeleteContact(string name)
: Deletes a contact with the given name
. Returns true
if the contact exists and is deleted, false
otherwise.Let's break down each method in detail in the next sections.
This method adds a new contact to the address book with the given name
and phoneNumber
. If the contact already exists, it returns false
. Otherwise, it adds the contact and returns true
.
Question: Why do you think we need to check if the contact already exists?
Answer: To avoid duplicating existing entries. Also, if a contact with the same name already exists, we shouldn't allow overwriting its phone number in this method, as it's only for creation.
Here is the method implementation:
C#1using System; 2using System.Collections.Generic; 3 4public class AddressBook 5{ 6 private Dictionary<string, string> contacts; 7 8 public AddressBook() 9 { 10 contacts = new Dictionary<string, string>(); 11 } 12 13 public bool AddContact(string name, string phoneNumber) 14 { 15 if (contacts.ContainsKey(name)) 16 { 17 return false; 18 } 19 contacts.Add(name, phoneNumber); 20 return true; 21 } 22 23 public IEnumerable<KeyValuePair<string, string>> GetAllContacts() 24 { 25 return contacts; 26 } 27} 28 29public class Program 30{ 31 public static void Main() 32 { 33 AddressBook addressBook = new AddressBook(); 34 Console.WriteLine(addressBook.AddContact("Alice", "123-456-7890")); // True 35 Console.WriteLine(addressBook.AddContact("Alice", "098-765-4321")); // False 36 foreach (var contact in addressBook.GetAllContacts()) 37 { 38 Console.WriteLine($"{contact.Key}: {contact.Value}"); // Alice: 123-456-7890 39 } 40 } 41}
In this method:
if (contacts.ContainsKey(name))
.false
.Dictionary
using contacts.Add(name, phoneNumber);
and return true
.This method retrieves the phone number associated with a given name
. If the contact does not exist, it returns null
.
Question: What do we gain by returning null
when a contact doesn't exist?
Answer: It provides a clear indicator that the contact is not in the address book, allowing us to handle such cases gracefully.
Here is the method implementation:
C#1using System; 2using System.Collections.Generic; 3 4public class AddressBook 5{ 6 private Dictionary<string, string> contacts; 7 8 public AddressBook() 9 { 10 contacts = new Dictionary<string, string>(); 11 } 12 13 public bool AddContact(string name, string phoneNumber) 14 { 15 if (contacts.ContainsKey(name)) 16 { 17 return false; 18 } 19 contacts.Add(name, phoneNumber); 20 return true; 21 } 22 23 public string? GetContact(string name) // Modify return type to allow null 24 { 25 contacts.TryGetValue(name, out string? phoneNumber); // Allow nullable type 26 return phoneNumber; 27 } 28} 29 30public class Program 31{ 32 public static void Main() 33 { 34 AddressBook addressBook = new AddressBook(); 35 addressBook.AddContact("Alice", "123-456-7890"); 36 Console.WriteLine(addressBook.GetContact("Alice")); // 123-456-7890 37 Console.WriteLine(addressBook.GetContact("Bob")); // empty line, as it's null 38 } 39}
In this method:
contacts.TryGetValue(name, out string phoneNumber);
, which tries to get the value for the key name
. If the key exists, it returns the phone number; otherwise, it returns null
.This method deletes a contact with the given name
. If the contact exists and is deleted, it returns true
. If the contact does not exist, it returns false
.
Question: What could be a real-world consequence of not checking if the contact exists before deletion?
Answer: One consequence can be assuming that a contact was removed when, in fact, it was never there, leading to inaccurate tracking of records.
Here is the method implementation:
C#1using System; 2using System.Collections.Generic; 3 4public class AddressBook 5{ 6 private Dictionary<string, string> contacts; 7 8 public AddressBook() 9 { 10 contacts = new Dictionary<string, string>(); 11 } 12 13 public bool AddContact(string name, string phoneNumber) 14 { 15 if (contacts.ContainsKey(name)) 16 { 17 return false; 18 } 19 contacts.Add(name, phoneNumber); 20 return true; 21 } 22 23 public string? GetContact(string name) // Modify return type to allow null 24 { 25 contacts.TryGetValue(name, out string? phoneNumber); // Allow nullable type 26 return phoneNumber; 27 } 28 29 public bool DeleteContact(string name) 30 { 31 return contacts.Remove(name); 32 } 33 34 public IReadOnlyDictionary<string, string> GetAllContacts() // Added method to retrieve contacts 35 { 36 return contacts; // Return the entire dictionary as read-only 37 } 38} 39 40public class Program 41{ 42 public static void Main() 43 { 44 AddressBook addressBook = new AddressBook(); 45 addressBook.AddContact("Alice", "123-456-7890"); 46 Console.WriteLine(addressBook.DeleteContact("Alice")); // True 47 Console.WriteLine(addressBook.DeleteContact("Bob")); // False 48 49 foreach (var contact in addressBook.GetAllContacts()) // Use GetAllContacts method 50 { 51 Console.WriteLine($"{contact.Key}: {contact.Value}"); // (Empty, as there are no contacts now) 52 } 53 } 54}
In this method:
return contacts.Remove(name);
, which removes the entry if the key exists and returns true
. If the key is not found, it returns false
.In this lesson, we explored creating a simple address book application using a C# Dictionary
. We implemented three key methods: AddContact
, GetContact
, and DeleteContact
to manage contacts effectively by focusing on adding, retrieving, and deleting entries. With the benefits of Dictionaries
, such as efficient operations, flexible key usage, and automatic handling of unique keys, we've demonstrated how to construct a robust address book application. Great work! Now, let's proceed to the practice exercises to reinforce your understanding.