Using Indexers in a Windows Application


Using Indexers in a Windows Application

In the following exercise, you will examine a simple phone book application and complete its implementation. Your task will be to write two indexers in the PhoneBook class: one that accepts a Name parameter and returns a PhoneNumber, and another that accepts a PhoneNumber parameter and returns a Name. (The Name and PhoneNumber structs have already been written.) You will also need to call these indexers from the correct places in the program.

Familiarize yourself with the application

  1. Start Microsoft Visual Studio 2005.

  2. Open the Indexers project, located in the \Microsoft Press\Visual CSharp Step by Step\Chapter 15\Indexers folder in your My Documents folder.

    This is a Microsoft Windows Forms application.

  3. On the Debug menu, click Start Without Debugging.

    The project builds and runs. A form displays two empty text boxes labeled Name and Phone Number. The form also contains three buttons—one to add a name/phone number pair to a list of names and phone numbers held by the application, one to find a phone number when given a name, and one to find a name when given a phone number. These buttons currently do nothing. Your task is to finish the application so that these buttons work.

  4. Close the form and return to Visual Studio 2005.

  5. Display the Name.cs source file in the Code and Text Editor window. Examine the Name struct. Its purpose is to act as a holder for names.

    The name is provided as a string to the constructor. The name can be retrieved by using the read-only string property called Text. (The Equals and GetHashCode methods are used for comparing Names when searching through an array of Name values—you can ignore them for the time being.)

  6. Display the PhoneNumber.cs source file in the Code and Text Editor window and examine the PhoneNumber struct. It is very similar to the Name struct.

  7. Display the PhoneBook.cs source file in the Code and Text Editor window and examine the PhoneBook class.

    This class contains two private arrays: an array of Name values called names, and an array of PhoneNumber values called phoneNumbers. The PhoneBook class also contains an Add method which adds a phone number and name to the phone book. This method is called when the Add button on the form is clicked. The enlargeIfFull method is called by Add to check whether the arrays are full when the user adds another entry. This method creates two new bigger arrays, copies the contents of the existing arrays to them, and then discards the old arrays.

Write the indexers

  1. In the PhoneBook.cs source file, add a public read-only indexer that returns a Name and accepts a single PhoneNumber parameter to the PhoneBook class. Leave the body of the get accessor blank.

    The indexer should look like this:

    sealed class PhoneBook {     ...     public Name this [PhoneNumber number]     {         get          {          }     }     ... }

  2. Implement the get accessor.

    The purpose of the accessor is to find the name that matches the specifed phone number. To do this, you will need to call the static IndexOf method of the Array class. The IndexOf method performs a search through an array, returning the index of the first item in the array that matches. The first argument to IndexOf is the array to search through (phoneNumbers). The second argument to IndexOf is the item you are searching for. IndexOf returns the integer index of the element if it finds it, otherwise IndexOf will return –1. If the indexer finds the phone number, it should return it, otherwise it should return an empty Name value. (Note that Name is a struct and will always have a default constructor that sets its private field to null.)

    The indexer with its completed get accessor should look like this:

    sealed class PhoneBook {     ...     public Name this [PhoneNumber number]     {         get         {             int i = Array.IndexOf(this.phoneNumbers, number);             if (i != -1)                 return this.names[i];             else                 return new Name();         }     }      ... }

  3. Add a second public read-only indexer to the PhoneBook class that returns a PhoneNumber and accepts a single Name parameter. Implement this indexer in the same way as the first one (again note that PhoneNumber is a struct and therefore always has a default constructor).

    The second indexer should look like this:

    sealed class PhoneBook {     ...     public PhoneNumber this [Name name]     {         get         {             int i = Array.IndexOf(this.names, name);             if (i != -1)                 return this.phoneNumbers[i];             else                  return new PhoneNumber();         }     }     ... }

    Notice that these overloaded indexers can co-exist because their signatures are different. If the Name and PhoneNumber structs were replaced by simple strings (which they wrap), the overloads would have the same signature and the class would not compile.

  4. On the Build menu, click Build Solution. Correct any syntax errors and then rebuild if necessary.

Call the indexers

  1. Display the Form1.cs source file in the Code and Text Editor window, and then locate the findPhone_Click method.

    This method is called when the first Search button is clicked. (This method is called by using events and delegates, which you will learn about in Chapter 16, “Delegates and Events.”) This method is currently empty. It should perform the following tasks:

    1. Read the Text string from the Name text box.

    2. If the string is not empty, then search for the phone number corresponding to that name in the PhoneBook by using the indexer (notice that Form1 contains a private PhoneBook field called phoneBook); construct a Name object from the string, and pass it as the parameter to the PhoneBook indexer.

    3. Write the PhoneNumber returned by the indexer to the phoneNumber text box.

  2. Implement the findPhone_Click method now.

    It should look like this:

    partial class Form1 : System.Windows.Forms.Form {     ...     private void findPhone_Click(object sender, System.EventArgs e)     {         string text = name.Text;         if (text != "")         {             phoneNumber.Text = phoneBook[new Name(text)].Text;         }     }     ...     private PhoneBook phoneBook = new PhoneBook(); }

  3. Locate the findName_Click method in the Form1.cs source file. It is below the findPhone_Click method.

    The findName_Click method is called when the second search button is clicked. This method should be similar to findPhoneClick:

    1. Read the Text string from the Phone Number text box.

    2. If the string is not empty, then search for the name corresponding to that phone number in the PhoneBook, by using the indexer.

    3. Write the Name returned by the indexer to the Name text box.

  4. Implement this method.

    It should look like this:

    partial class Form1 : System.Windows.Forms.Form {     ...     private void findName_Click(object sender, System.EventArgs e)     {         string text = phoneNumber.Text;         if (text != "")         {             name.Text = phoneBook[new PhoneNumber(text)].Text;         }     }     ... }

  5. On the Build menu, click Build Solution.

Run the application

  1. On the Debug menu, click Start Without Debugging.

  2. Type your name and phone number into the text boxes, and then click the Add button.

    When you click the Add button, the Add method puts the entries into the phone book and clears the text boxes so that they are ready to perform a search.

  3. Repeat Step 2 a few times with some different names and telehone numbers so that the phone book contains a number of entries.

  4. Type a name you used in Step 2 into the Name text box, and then click the Search -> button.

    The phone number you added in Step 2 is retrieved from the phone book and is displayed in the Phone Number text box.

  5. Clear the name from the Name text box, and then click the <- Search button.

    The name is retrieved from the phone book and is displayed in the Name text box.

  6. Type a name that you did not enter in the phone book into the Name text box, and then click the Search -> button.

    This time the Phone Number text box is empty, indicating that the name could not be found in the phone book.

  7. Close the form.

  • If you want to continue to the next chapter

    Keep Visual Studio 2005 running and turn to Chapter 16.

  • If you want to exit Visual Studio 2005 now

    On the File menu, click Exit. If you see a Save dialog box, click Yes.




Microsoft Visual C# 2005 Step by Step
Microsoft® Visual C#® 2005 Step by Step (Step By Step (Microsoft))
ISBN: B002CKYPPM
EAN: N/A
Year: 2005
Pages: 183
Authors: John Sharp

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net