Generica in .NET Framework

When we look at the term “generic“, unrelated to the programming world, it simply means something that is not tied to any sort of brand name. For example, if we purchase some generic dish soap, soap that has no brand name on it, we know that we are buying dish soap and expect it to help us clean our dishes, but we really don’t know what exact brand (if any) will be inside the bottle itself. We can treat it as dish soap even though we don’t really have any idea of its exact contents.

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, type casting).

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, 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:

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)

If we had a User object, you could create another class (which implements IEnumerable and IEnumerator, or just IList) that allows you to only add and access User objects, even though most implementations will still store them as objects. It is a lot of work implementing these two interfaces, and you can imagine the work needed to create this additional collection class every time you wanted a Type-safe collection. The third and final way of creating a collection of items is by simply creating an array of that type, for example:

string[] mystrings = new string[]{“a”, “b”, “c”};

This will guarantee Type safety, but is not very reusable nor very friendly to work with. Adding a new item to this collection would mean needing to create a temporary array and copy the elements into this new temporary array, resizing the old array, copying the data back into it, and then adding the new item to the end of that collection. In my humble opinion, this is too much work that tends to be very error prone.


System.Collections.ArrayList Class


Leave a Reply

Your email address will not be published. Required fields are marked *