Lesson Weekend

To explore how to use dictionaries in an application, we'll create a phone book program for users to keep track of their friends' contact information.

Using a Dictionary in an Application


Application Setup

First we'll need a file. Let's create a folder called phonebook with the files PhoneBook.csproj and PhoneBook.cs. Add the following code:

PhoneBook.cs
using System;
using System.Collections.Generic;

class PhoneBook
{
  public static Dictionary<string, string> phoneNumbers = new Dictionary<string, string>();

  static void Main()
  {

  }
}

Importing Namespaces

Notice we've added the line using System.Collections.Generic; to our standard program format. This tells our program to load the part of the C# language that allow us to use a Dictionary object.

Specifically, System.Collections.Generic is a namespace built within .NET. We will cover namespaces in more detail later. For now, just know we must add the line using System.Collections.Generic; to any program file that uses a Dictionary.

Scope

Let's take another look at our PhoneBook.cs code:

PhoneBook.cs
using System;
using System.Collections.Generic;

class PhoneBook
{
  public static Dictionary<string, string> phoneNumbers = new Dictionary<string, string>();

  static void Main()
  {

  }
}

Notice the phoneNumbers dictionary is declared outside any methods. This is to ensure it has the correct scope. Because it's placed just inside our PhoneBook class, methods declared in this class will be able to refer to it. If it were inside another class, methods from this class wouldn't be able to access it. A static variable like this is also sometimes referred to as a class variable because it is scoped to the level of the class. While static variables can be very useful, we should only use them if the variables need to be accessed everywhere in the class. Otherwise, we should try to scope our variables more locally inside of methods.

Methods

Next, let's consider what our program should do. Do you have any ideas? We think a standard address book program should be able to:

  • Add new contacts, including their name, number, address.
  • Recall and display that contact information to the user as necessary.

We'll need three methods:

  1. Our standard Main() method will handle interacting with the user in the console.
  2. An AddContact() method will add a new contact.
  3. A LookUpContact() method will look up a contact and display their information.

Let's add these methods now:

PhoneBook.cs
using System;
using System.Collections.Generic;

class Phonebook
{
  public static Dictionary<string, string> phoneNumbers = new Dictionary<string, string>();

  static void Main()
  {
    //nothing here yet.
  }

  static void AddContact()
  {
    //nothing here yet.
  }

  static void LookUpContact()
  {
    //nothing here yet.
  }
}

Main()

We'll add the following code to the Main() method:

PhoneBook.cs
...

static void Main()
{
  Console.WriteLine("MAIN MENU");
  Console.WriteLine("Would you like to add a person to your phone book? ['Y' for yes, 'Enter' for no]");
  string answer = Console.ReadLine();
  if (answer == "Y" || answer == "y")
  {
    AddContact();
  }
  else
  {
    Console.WriteLine("Would you like to look up a number in your phone book? ['Y' for yes, 'Enter' for no]");
    string lookUpAnswer = Console.ReadLine();
    if (lookUpAnswer == "Y" || lookUpAnswer == "y")
    {
      LookUpContact();
    }
    else
    {
      Console.WriteLine("Are you finished with this program? ['Y' for yes, 'Enter' for no]");
      string finishedAnswer = Console.ReadLine();
      if (finishedAnswer == "Y" || finishedAnswer == "y")
      {
        Console.WriteLine("Goodbye.");
      }
      else
      {
        Main();
      }
    }
  }
}

...

We need to be able to collect information from the user. A standard way to do this is with a simple [Y] user query. This may look complex at first glance, but it's actually review:

  • Main() will print "MAIN MENU" and then ask the user if they want to add a contact.

  • The program instructs users to enter "Y" if they want to add a new contact. If the user does so, the program will take the user to the AddContact() method.

  • If the user enters a value other than "Y" or "y", they're asked if they'd like to instead look up a contact. If they choose "Y" here, they're taken to our LookUpContact() method.

  • If the user does not choose to add or look up a contact, they're given a chance to safely exit the program. If they do not want to exit the program, the Main() method is called and the options begin again.

AddContact()

Next we'll build our AddContact() method:

PhoneBook.cs
...

static void AddContact()
{
  Console.WriteLine("NEW CONTACT");
  Console.WriteLine("Enter a new contact name");
  string name = Console.ReadLine();
  Console.WriteLine("Enter a new contact phone number");
  string number = Console.ReadLine();
  if (phoneNumbers.ContainsKey(name))
  {
    Console.WriteLine("That person is already in your phonebook. Their number is " + phoneNumbers[name]);
  }
  else
  {
    phoneNumbers.Add(name, number);
  }
  Main();
}

...

Here we use Console.ReadLine()to collect a name and phone number for the new contact.

  • We print "NEW CONTACT" in the console, then ask for the contact information.

  • There's a new method here called ContainsKey(). This is a built-in dictionary method that looks through the dictionary it's called upon to see if the dictionary contains the key provided as an argument. It returns a boolean that denotes whether the key already exists in the dictionary.

  • If this boolean is true, our program will tell the user that this person is already in our address book.

  • If the boolean returns false, we add the contact to the dictionary with the code phoneNumbers.Add(name, number);.

  • When the method has finished adding or displaying the contact, Main() is called again to send us back to the beginning, essentially looping the program until the user quits (with Ctrl + C).

LookUpContact()

Now let's write our LookUpContact() method:

PhoneBook.cs
...

static void LookUpContact()
{
  Console.WriteLine("CONTACT LOOKUP");
  Console.WriteLine("Whose number would you like to look up?");
  string friend = Console.ReadLine();
  if (phoneNumbers.ContainsKey(friend))
  {
    string value = phoneNumbers[friend];
    Console.WriteLine(friend + "\'s phone number is " + value);
  }
  else
  {
    Console.WriteLine("That person is not in your phone book.");
  }
  Main();
}

...

  • We print "CONTACT LOOKUP", then ask for the contact by name.

  • We query the dictionary with ContainsKey(). Depending on the value of the boolean, we either print the contact information or alert the user that the contact name they're looking for does not exist.

  • When the method has completed, it calls Main() to start the program over.

The entire completed file should look like this:

PhoneBook.cs
using System;
using System.Collections.Generic;

class Phonebook
{
  public static Dictionary<string, string> phoneNumbers = new Dictionary<string, string>();

  static void Main()
  {
    Console.WriteLine("MAIN MENU");
    Console.WriteLine("Would you like to add a person to your phone book? ['Y' for yes, 'Enter' for no]");
    string answer = Console.ReadLine();
    if (answer == "Y" || answer == "y")
    {
      AddContact();
    }
    else
    {
      Console.WriteLine("Would you like to lookup a number in your phone book? ['Y' for yes, 'Enter' for no]");
      string lookUpAnswer = Console.ReadLine();
      if (lookUpAnswer == "Y" || lookUpAnswer == "y")
      {
        LookUpContact();
      }
      else
      {
        Console.WriteLine("Are you finished with this program? ['Y' for yes, 'Enter' for no]");
        string finishedAnswer = Console.ReadLine();
        if (finishedAnswer == "Y" || finishedAnswer == "y")
        {
          Console.WriteLine("Goodbye.");
        }
        else
        {
          Main();
        }
      }
    }
  }

  static void AddContact()
  {
    Console.WriteLine("NEW CONTACT");
    Console.WriteLine("Enter a new contacts name");
    string name = Console.ReadLine();
    Console.WriteLine("Enter a new contacts phone number");
    string number = Console.ReadLine();
    if (phoneNumbers.ContainsKey(name))
    {
      Console.WriteLine("That person is already in your phonebook. Their number is " + phoneNumbers[name]);
    }
    else
    {
      phoneNumbers.Add(name, number);
    }
    Main();
  }

  static void LookUpContact()
  {
    Console.WriteLine("CONTACT LOOKUP");
    Console.WriteLine("Whose number would you like to look up?");
    string friend = Console.ReadLine();
    if (phoneNumbers.ContainsKey(friend))
    {
      string value = phoneNumbers[friend];
      Console.WriteLine(friend + "\'s phone number is " + value);
    }
    else
    {
      Console.WriteLine("That person is not in your phone book.");
    }
    Main();
  }
}

Try it out using:

$ dotnet run

Now we have all the basic tools for working with collections of data in our programs!

Lesson 7 of 9
Last updated more than 3 months ago.