320
LESSON 27 Using interfaces
To make recognizing interface names easy, you should begin interface names
with
I as in IDomicile, IComparable, and IWhatever.
Defining the property but not implementing it may seem like no big deal, but it lets your code treat
all
IDomicile objects in a uniform way. Instead of writing separate functions to work with Duplex,
RusticCabin, and HouseBoat objects, you can write a single function that manipulates objects that
implement
IDomicile.
That brings us to the second big advantage provided by interfaces: code generalization.
Code Generalization
Interfaces can make your code more general while still providing type checking. They let you treat
objects that have common features as if they were of the interface type rather than their true indi-
vidual types.
For example, suppose you write the following method that displays an array of strings in a
ListBox:
private void DisplayValues(string[] items)
{
itemsListBox.Items.Clear();
foreach (string item in items)
{
itemsListBox.Items.Add(item);
}
}
This function works reasonably well, but suppose you later decide that you need to display the items
that are in a
List<string> instead of an array. You could write a new version of the function that was
nearly identical to this one but that works with a list instead of an array as in the following code:
private void DisplayValues(List<string> items)
{
itemsListBox.Items.Clear();
foreach (string item in items)
{
itemsListBox.Items.Add(item);
}
}
If you compare these two functions you’ll see that they are practically identical, so if you use them
you must write, debug, and maintain two pieces of code that do almost exactly the same thing.
This is where interfaces can help.
Look again at the two functions. They differ only in their parameter definitions and the rest of their
code is the same. The reason is that the functions don’t really care that the parameters are arrays or
lists. All they really care about is that you can use a
foreach loop to iterate through them.
The
IList<> interface requires that a class provide various list-like features such as Clear, Add, and
RemoveAt methods. It also requires support for foreach.
596906c27.indd 320 4/7/10 12:34:07 PM