Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 105
VB:
Sub ProcessPayrollForAllAccounts()
Dim accounts As IAccount() = GetAllAccounts()
For Each account In accounts
account.Credit(1000)
Next
End Sub
Function GetAllAccounts() As IAccount()
Dim allAccounts(3) As IAccount
allAccounts(0) = New Checking()
allAccounts(1) = New Saving()
allAccounts(2) = New Checking()
allAccounts(3) = New Saving()
Return allAccounts
End Function
You can call the code in Listing 4-6 from the Main method like this:
C#:
Program bank = new Program();
bank.ProcessPayrollForAllAccounts();
VB:
ProcessPayrollForAllAccounts()
Examining Listing 4-6, you can see that accounts is an array of IAccount. While
you can’t instantiate an interface by itself, you can assign an instance of the class that
implements that interface using a variable simply declared as the interface type. In this
case, GetAllAccounts returns a list of objects that implement IAccount.
Looking inside of the GetAllAccounts method, you can see how an array is being built
with both Checking and Saving objects. Since Checking and Saving implement IAccount,
which you saw in Listings 4-3 and 4-4, instances of Checking and Saving can be directly
assigned into elements of an IAccount array.
Back in the ProcessPayrollForAllAccounts method, you can see a loop iterate through
each IAccount instance, calling Credit. The reason you can call Credit like this is that
IAccount defines a contract for the Credit method. Calling Credit on each instance really