Home > .NET Framework > CLR Generics – Enter generics

CLR Generics – Enter generics

Generics offer an elegant solution to the problems mentioned here. A generic version of the odd number code written above will be like this.

List list = new List();
1. list.Add(3);
2. list.Add(1);
3. list.Add(5);
4. int oddNumber = list[0];

The important difference here is that lines labeled 1, 2 and 3 do not result in boxing operations. Line labeled 4 doesn’t require a unbox, cast and type compatibility check.

The reference type example written using the Generic collections in the BCL.

List list = new List();
1. list.Add(aCustomerObject);
2. list.Add(anotherCustomerObject);
// This would result in a compile error
3. list.Add(anOrderObject);
4. aListControl.DataSource = list
5. aListControl.DataBind();

Line labeled 3 results in a compile time error. This is the type safety offered by the strongly typed generic collections library of the BCL. Its time to introduce some terms in the CLR Generics world. That’ll be in the next entry, till then bye.

Categories: .NET Framework
  1. No comments yet.
  1. November 19, 2010 at 10:59 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: