HI WELCOME TO SIRIS

Advantages and disadvantages of using generics in C#

Leave a Comment


In Microsoft.NET version 1.0 there were collections, such as the ArrayList for working with groups of objects. An ArrayList is much like an array, except it could automatically grow and offered many convenience methods that arrays don't have. The problem with ArrayList and all the other .NET v1.0 collections is that they operate on type object. Since all objects derive from the object type, you can assign anything to an ArrayList. The problem with this is that you incur performance overhead converting value type objects to and from the object type and a single ArrayList could accidentally hold different types, which would cause a hard to find errors at runtime because you wrote code to work with one type. Generic collections fix these problems.


A generic collection is strongly typed (type safe), meaning that you can only put one type of object into it. This eliminates type mismatches at runtime. Another benefit of type safety is that performance is better with value type objects because they don't incur overhead of being converted to and from type object. With generic collections, you have the best of all worlds because they are strongly typed, like arrays, and you have the additional functionality, like ArrayList and other non-generic collections, without the problems.


It is always good to use generics rather than using ArrayList,Hashtable etc, found in System.Collections namespace. The only reason why you may want to use System.Collections is for backward compatibility.

I cannot think of any disadvantages of using generics at the moment. Please feel free to comment if you are aware of any disadvantages.

The screen shot below shows, the generics collection classes and their respective non generic counterparts.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.