New Features in C# 2.0—Type-Safe List: How do I do that?

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.

How do I do that?

To get a feel for the new generic types in .NET 2.0, let’s use the typesafe List class to create a list of employees. To execute this lab, open Visual Studio 2005, create a new C# Console application, and name it CreateATypeSafeList. Replace the code Visual Studio 2005 creates for you with the code in Example 1-1.

TIP
You must use the System.Collections.Generic namespace to use the generic types. By default Visual Studio 2005 adds this namespace to all projects.


Example 1-1. Creating a type-safe list

using System;
using System.Collections.Generic;
 
namespace CreateATypeSafeList
{
  // a class to store in the List
  public class Employee
  {
    private int empID;
    // constructor
    public Employee(int empID)
    {
      this.empID = empID;
    }
    // override the ToString method to
    // display this employee's id
    public override string ToString( )
    {
      return empID.ToString( );
    }
  } // end class
 
  // Test driver class
  public class Program
  {
    // entry point
    static void Main( )
    {
      // Declare the type safe list (of Employee objects)
      List<Employee> empList = new List<Employee>( );
 
      // Declare a second type safe list (of integers)
      List<int> intList = new List<int>( );
 
      // populate the Lists
      for (int i = 0; i < 5; i++)
      {
        empList.Add(new Employee(i + 100));
        intList.Add(i * 5);
        // empList.Add(i * 5); // see "What About" section below
      }
 
      // print the integer list
      foreach (int i in intList)
      {
        Console.Write("{0} ", i.ToString( ));
      }
      Console.WriteLine("\n");
 
      // print the Employee List
      foreach (Employee employee in empList)
      {
        Console.Write("{0} ", employee.ToString( ));
      }
      Console.WriteLine("\n");
    }
  }
}

Output:

0 5 10 15 20
100 101 102 103 104
TIP
All the source code for the labs in this chapter is available on my web site, http://www.LibertyAssociates.com. Click Books, and then scroll down to C# 2.0 Programmer’s Notebook and click Source to save the source code to your computer.

Once unzipped, the source code is in chapter folders, and each lab folder is named with the namespace shown in the listing. For instance, for Example 1-1, the source is stored in Chapter 1\ CreateATypeSafeList.

While you are at my site, you can also read the FAQ list and errata sheet and join a private support discussion forum.


Previous_Page_.gif Next_Page_.gif

Personal tools