Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 4: Learning Just Enough C# and VB.NET: Intermediate Syntax 109
Coding Generics
Generics are language features that allow you to write a piece of code that will work with
multiple types efficiently. A generic class definition has a placeholder for the type you
want it to represent, and you use this placeholder to declare the type you want to work
with. There is an entire library of generic collections in .NET as well as generic types
across the entire .NET Framework Class library. Because of the volume of information
required for comprehensive coverage of generics, this section will only serve as a brief
introduction, giving you an example of generic use that you’re most likely to see in the
future. Listing 4-8 demonstrates how to declare a generic List. The code specifies the
type of the list as a Checking account and then proceeds to populate the generic list and
perform operations on the Checking elements of the generic list. Remember to include a
using directive (imports for VB) for the System.Collections.Generic namespace near the
top within your file.
Listing 4-8 Coding a generic list collection
C#:
private void ListDemo()
{
List<Checking> checkAccts = new List<Checking>();
checkAccts.Add(new Checking());
checkAccts.Add(new Checking());
for (int i = 0; i < checkAccts.Count; i++)
{
Console.WriteLine(checkAccts[i].CurrentBalance);
}
}
VB:
Sub ListDemo()
Dim checkAccts As New List(Of Checking)
checkAccts.Add(New Checking())
checkAccts.Add(New Checking())
For i As Integer = 0 To checkAccts.Count - 1
Console.WriteLine(checkAccts(i).CurrentBalance)
Next
End Sub