Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 101
In the C# listing, following the class name by a colon and then the interface name
specifies that the class will implement the interface. The VB listing uses the Implements
keyword to indicate that Checking and Saving classes implement the IAccount interface.
Looking at both Checking and Saving, you can see that they have the Credit, Debit, and
CurrentBalance members that are specified in IAccount. The primary difference is that
IAccount doesn’t have an implementation, but you wrote an implementation for Checking
and Saving. Listings 4-3 and 4-4 simplify the implementation of the interface so that you
don’t have to read a lot of code that doesn’t add to the purpose of the listing to show you
how a class implements an interface. In reality, the code in the methods would be different
for Checking and Saving because they are different account types with different business
rules.
You’ve created an interface and written classes to implement the contract of that
interface. The next section gives you a couple of examples to help clarify the practical use
of interfaces.
Writing Code That Uses an Interface
One of the best ways to understand the value of interfaces is to see a problem that
interfaces solve. In this section, I’ll show you some code that accesses the Checking and
Saving classes individually, essentially duplicating code. Then I’ll show you how to write
the code a single time with interfaces. The particular example runs a payroll by obtaining
instances of Checking and Saving classes and crediting each class, which is synonymous
with employees being paid. Starting with the bad example, Listing 4-5 shows how this
code works.
Listing 4-5 Processing payroll with explicit checking and saving class instances
C#:
public void ProcessPayrollForCheckingAndSavingAccounts()
{
Checking[] checkAccounts = GetCheckingAccounts();
foreach (var checkAcct in checkAccounts)
{
checkAcct.Credit(500);
}