Microsoft 9GD00001 Computer Accessories User Manual


 
96 Microsoft Visual Studio 2010: A Beginner’s Guide
As you can see, the Editor pops up a tooltip instructing you to type TAB to create a new
delegate instance. Type
TAB and Code Completion will pop up another tooltip for creating
the handler method, as shown in Figure 4-2.
In Figure 4-2, you can see that Code Completion is suggesting a method name for you.
You have a choice of pressing
TAB or changing the method name and then pressing TAB.
Either way, you have a fast way to hook up a handler method to an event via the event’s
delegate type.
Just as a delegate provides an interface to a method that is a contract basically to
describe how to communicate, you can also define interfaces to classes to communicate
with them in a specified way, and these are intuitively named . . . interfaces.
Implementing Interfaces
Another language feature that gives you flexibility is interfaces. An interface can be useful
if you want to have a group of classes that can be interchanged at any time, yet you need
to write the same operations for each of these classes. Essentially, you want to write the
code that uses the class only one time, but still switch what the actual class is. That’s where
interfaces come in. The interface creates a contract that each of the interchangeable classes
must adhere to. So, if the interface says that all classes that implement the interface have
method A and property B, then every class that implements the interface must have method
A and property B; the compiler enforces this like a contract that cannot be broken. The
following sections show you how to write an interface and then build a couple of classes
that implement that interface. Finally, you’ll see how to write code against the interface.
One important fact to remember about interfaces is that they don’t have any code other
than definitions of members. This definition of members is the contract of the interface.
You are the one who must to write a class that contains the members of the interface, and
you must write the code that provides an implementation of the interface members. A
common point of confusion is that an interface does not have any executable code, but the
classes that implement the interfaces do.
The following sections show you how to create an interface, how to create a class that
has code (that you’ve written) to implement the interface contract, and how to write code
that operates on the classes that implement (guarantee the contract of) the interface.
Figure 4-2 Code completion for handler method creation