Thursday, October 30, 2008

Generics in .NET 2.0

What Are Generics?
Generics allow you to realize type safety at compile time. They allow you to create a data structure without committing to a specific data type. When the data structure is used, however, the compiler makes sure that the types used with it are consistent for type safety. Generics provide type safety, but without any loss of performance or code bloat. While they are similar to templates in C++ in this regard, they are very different in their implementation.

The short answer is this: "without generics, it is very difficult to create type-safe collections".

Creating Our First Generic Type:

public class Col {
T t;
public T Val{get{return t;}set{t=value;}}
}


public class ColMain {
public static void Main() {
//create a string version of our generic class
Col mystring = new Col();
//set the value
mystring.Val = "hello";

//output that value
System.Console.WriteLine(mystring.Val);
//output the value's type
System.Console.WriteLine(mystring.Val.GetType());

//create another instance of our generic class, using a different type
Col myint = new Col();
//load the value
myint.Val = 5;
//output the value
System.Console.WriteLine(myint.Val);
//output the value's type
System.Console.WriteLine(myint.Val.GetType());

}
}


When we compile the two classes above and then run them, we will see the following output:

hello
System.String
5
System.Int32

Generic Collections:

User.cs


namespace Rob {
public class User {
protected string name;
protected int age;
public string Name{get{return name;}set{name=value;}}
public int Age{get{return age;}set{age=value;}}
}
}


Main.cs

public class M {
public static void Main(string[] args) {
System.Collections.Generic.List users = new System.Collections.Generic.List();
for(int x=0;x<5;x++) {
Rob.User user = new Rob.User();
user.Name="Rob" + x;
user.Age=x;
users.Add(user);
}

foreach(Rob.User user in users) {
System.Console.WriteLine(System.String.Format("{0}:{1}", user.Name, user.Age));
}
System.Console.WriteLine("press enter");
System.Console.ReadLine();

for(int x=0;x System.Console.WriteLine(System.String.Format("{0}:{1}", users[x].Name, users[x].Age));
}

}
}


Output

Rob0:0
Rob1:1
Rob2:2
Rob3:3
Rob4:4
press enter

Rob0:0
Rob1:1
Rob2:2
Rob3:3
Rob4:4