Microsoft 9GD00001 Computer Accessories User Manual


 
106 Microsoft Visual Studio 2010: A Beginner’s Guide
invokes the Credit method on the runtime Checking or Saving instance. Your code that
you wrote for Checking.Credit and Saving.Credit will execute as if your code called them
directly as in Listing 4-5. Also observe that we’ve eliminated the duplication because one
algorithm, namely IAccount.Credit() in our example, works on both Checking and Saving
objects.
Now you can see that interfaces help you treat different types of objects as if they were
the same type and helps you simplify the code you need to write when interacting with
those objects, eliminating duplication. Imagine what would happen if you were tasked
with adding more bank account types to this algorithm without interfaces; you would need
to go into the algorithm to write duplicate code for each account type. However, now you
can create the new account types and derive them from IAccount; the new account types
automatically work in the same algorithm.
The interface Snippet
Before using the interface snippet, open a new file by right-clicking your project in VS
Solution Explorer, select Add | New Item | Code File, and name the file IInvestment.cs
(or IInvestment.vb in VB). You’ll have a blank file to work with. To use the interface
snippet, type int and press
TAB, TAB; you’ll see a snippet template similar to Figure 4-3
(C#) or Figure 4-4 (VB).
Because prefixing interfaces with I is an expected convention, the template highlights
the identifier after I.
Figure 4-3 The C# interface snippet template
Figure 4-4 The VB interface snippet template