October 07, 2008

Generics Explanation benefit limitation

Generics: part of dot net type system where we have option to leave the type of member.
And that can be given by the consumer code.

Strong Type objects
type Safety.

Only the objects of the class will be allowed that was mentioned while declaring the object.

We can have other objects in the generics
Why.
• Reduced run-time errors The compiler cannot detect type errors when you cast to and from the Object class. For example, if you cast a string to an Object class and then attempt to cast that Object to an integer, the compiler will not catch the error. Instead, the runtime will throw an exception. Using generics allows the compiler to catch this type of bug before your program runs. Additionally, you can specify constraints to limit the classes used in a generic, enabling the compiler to detect an incompatible type.
• Improved performance Casting requires boxing and unboxing which steals processor time and slows performance. Using generics doesn't require casting or boxing, which improves run-time performance.

Limitation:

Essentially, you are limited to the capabilities of the base Object class when writing generic code
So we could not use the + or > operator.

Generics is CLR Supported: Generics is supported by CLR itself. so its not a wrapper kind of thing like properties,namespace etc. Its recognized by the CLR. So in Meta Data Generics class is IL-ed. In realty its will be impossible to do that. Because a generic class can be instantiated with many types so it will blot the IL.

Generic Collection: Entire collection library was rewritten for the Generics.
Here is comparison list :
System.Collections vs. System.Collection.Generic or
Weakly vs Strongly type

ArrayList List
Hashtable Dictionary
Queue Queue
Stack Stack
SortedList SortedList
IEnumerable IEnumerable
IList IList
CollectionBase Collection

New Classes In Genric that do not have non generic equivalent.

SortedDictionary
KeyedCollection
LinkedList


Framework :2.0+
Visual studio: 2005 and 2008
please comment if you have any doubt and further want info. it will be updated very soon after your questions.

No comments: