Generics like support in .NET 1.0/1.1

Lot of my peers think that Generics support is cool and is only available in .NET 2.0. But there is a way to simulate strongly typed collections in .NET 1.0/1.1. Traditionally, we all use ArrayList to store objects (classes with public properties). But, unfortunately, ArrayList is a weak type and supports any object. So, we lose all the type safety that is available in Generics. Instead of using ArrayList, we can derive our classes from CollectionBase or ReadOnlyCollectionBase abstract classes. This class is strongly typed and provides type safety at compile time.


public class Employees: CollectionBase
{
public Employees()
{
.......
}


public int Add (Employee emp)
{
return List.Add (emp);
}


public int Remove (Employee emp)
{
return List.Remove (emp);
}
....
}

There is one caveat: Even though from the outside, you get strong reference, internally the IList type is still an object. But, it is still better than using ArrayList which is a weak reference type.

Advertisements

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: