Home > .NET Framework > CLR Generics – Motivation

CLR Generics – Motivation

A life without generics:
A Value Types example:
ArrayList list = new ArrayList();
1. list.Add(3);
2. list.Add(1);
3. list.Add(5);
list.Sort();
4. int oddNumber = (int)list[0];
The problem with the above code is
lines labeled 1, 2, 3 result in a boxing instruction. Because ArrayList.Add takes an object. Since 3, 1, 5 are integers (read value types) they will be boxed first. Likewise line labeled 4 notice results in an unbox operation because the indexer returns an object. Also cast operation requires a type compatibility check too.

A Reference Types example:

ArrayList list = new ArrayList();
1. list.Add(aCustomerObject);
2. list.Add(anotherCustomerObject);
...
3. list.Add(anOrderObject);
...
// Oops what happens now?
4. aListControl.DataSource = list
5. aListControl.DataBind();
An ArrayList is not a strongly typed collection. What the hell that does mean? An array list can hold objects of multiple types. There is no check offered by the compiler which prevents you from adding an order object to a list in which you intend to store only customer objects. This throws an exception at runtime when the databinding happens. A strongly typed implementation would be caught at compile time (line 3 should give a compile error).

Code duplication:
The only way one could work around this problem in a pre generic world is by writing strongly typed collections deriving from CollectionBase or directly implementing IList. This class has to written one for each type for ex. CustomerCollection, OrderCollection. This is unneccesary code duplication. But you had to live with it if you were to get the benefits of compile time type checking.

Advertisements
Categories: .NET Framework
  1. No comments yet.
  1. November 19, 2010 at 10:59 pm
  2. November 19, 2010 at 11:09 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: