Monday, June 7, 2010

Generic

What are Generic and when to use it.

A perfect example of where we would need Generics is in dealing with collections of items (integers, strings, Orders etc.).
We can create a generic collection than can handle any Type in a generic and Type-Safe manner.
For example, we can have a single array class that we can use to store a list of Users or even a list of Products, and when we actually use it, we will be able to access the items in the collection directly as a list of Users or Products, and not as objects (with boxing/unboxing, casting).


Previous problems
1)It requires that you store everything in it as an object
2)You need to cast up in order to get your object back to its actual Type
3)Performance is really lacking, especially when iterating with foreach()
4)It performs no type safety for you (no exceptions are thrown even if you add objects of different types to a single list)

System.Collections.ArrayList list = new System.Collections.ArrayList();
list.Add("a string");
list.Add(45); //no exception thrown
list.Add(new System.Collections.ArrayList()); //no exception
foreach(string s in list) { //exception will be thrown!
System.Console.WriteLine(s);


The ideal situation is for us to be able to create this generic collection functionality once and never have to do it again
-----------------
Generic Class

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

"Col" is our first indication that this Type is generic

This Type placeholder "T" is used to show that if we need to refer to the actual Type that is going to be used when we write this class, we will represent it as "T"

Notice on the next line the variable declaration "T t;" creates a member variable with the type of T, or the generic Type which we will specify later during construction of the class

final item in the class is the public property. Again, notice that we are using the Type placeholder "T" to represent that generic type for the type of that property. Also notice that we can freely use the private variable "t" within the class.


In order to use this class to hold any Type, we simply need to create a new instance of our new Type, providing the name of the Type within the "<>" brackets and then use that class in a Type-safe manner. For example:


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());

}
}

No comments:

Post a Comment