Advantages and disadvantages of using generics in C#
To better understand the advantages and disadvantages of
generics, it is better you read the below 2 articles first.
1. Click here to read about Advantages and disadvantages of
Arrays
2. Click here to read about Advantages and disadvantages of
System.Collections
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.
No comments:
Post a Comment