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
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