Saturday, April 5, 2008

Generics

Generics allows you to make an object a specific type. This allows intellisense to work on the object; which will also do type checking at compile time (meaning it won't build if you are trying to do something like assign an int to a string).

Before:
ArrayList people = new ArrayList();
people.Add("Moeykens");

string person = (string)people[0];
// Note: Without casting to string, you 
// will get error: "Cannot convert source 
// type 'object' to target type 'string'"
After:
List<string> people = new List<string>(); 
people.Add("Moeykens"); 
string person = people[0]; 

Compare the tooltips for each Add method.
Before:

After:


More Info:MSDN: Generics