New Features in C# 2.0—Type-Safe List: What just happened?

Microsoft .NET Framework, ASP.NET, Visual C# (CSharp, C Sharp, C-Sharp) Developer Training, Visual Studio


Jump to: navigation, search
CSharp-Online.NET:Tutorials
C# Tutorials

New Features in C# 2.0

© 2005 O'Reilly Media, Inc.

What just happened?

This listing creates two classes: an Employee class to be held in the collection and the Program class created by Visual Studio 2005. It also uses the List class provided by the .NET Framework Class Library.

The Employee class contains a single private field (empID), a constructor, and an override of ToString to return the empID field as a string.

First you create an instance of List that will hold Employee objects. The type of empList is "List of Employee Objects" and is declared thus:

List<Employee> empList

When you see the definition List<T>, the T is a placeholder for the actual type you’ll place in that list.

As always, empList is just a reference to the object you create on the heap using the new keyword. The new keyword expects you to invoke a constructor, which you do as follows:

new List<Employee>( )

This creates an instance of "List of Employee Objects" on the heap, and the entire statement, put together, assigns a reference to that new object to empList:

List<Employee> empList = new List<Employee>( );
TIP
This is just like writing:
Dog milo = new Dog( );

in which you create an instance of Dog on the heap and assign it to the reference to Dog, milo.


In the next statement, you create a second List, this time of type "List of Integers":

List<int> intList = new List<int>( );

Now you are free to add integers to the list of integers, and Employee objects to the list of Employee objects. Once the lists are populated, you can iterate through each of them, using a foreach loop to display their contents in the console window:

foreach (Employee employee in empList)
{
  Console.Write("{0} ", employee.ToString( ));
}


Previous_Page_.gif Next_Page_.gif

Personal tools