
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
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
Listing
C#:
public void ProcessPayrollForCheckingAndSavingAccounts()
{
Checking[] checkAccounts = GetCheckingAccounts();
foreach (var checkAcct in checkAccounts)
{
checkAcct.Credit(500);
}