affiliate_link

Thursday, April 22, 2010

What Are Generics?

Think of Generics in this manner. We can refer to a class, where we don't force it to be related to any specific Type, but we can still perform work with it in a Type-Safe manner. 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).

"Generic" Collections as we see them today

Currently, if we want to handle our Types in a generic manner, we always need to cast them to a System.Object, and we lose any benefit of a rich-typed development experience. For example, I'm sure most of us are familiar with the System.Collection.ArrayList class in Framework v1 and v1.1. If you have used it at all, you will notice a few things about it:

-----------------------------------------------------------------------------------
public class Col
{
T t;

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

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
Col cStr = new Col();
cStr.Val = "some text";
this.listBox1.Items.Add(cStr.Val.ToString());
this.listBox1.Items.Add(cStr.GetType().ToString());

Col cInt = new Col();
cInt.Val = 100;
this.listBox1.Items.Add(cInt.Val.ToString());
this.listBox1.Items.Add(cInt.GetType().ToString());
}
}
-----------------------------------------------------------------------------------

Reference: http://www.15seconds.com/issue/031024.htm