Thursday, October 8, 2009

Generics in Dot Net

GENERICS IN .NET

The Microsoft .NET Framework version 2.0 extends the .NET Framework version 1.1 with new features, improvements to existing features, and enhancements.
One of the new feature included in the the new version is Generics.

Generics and Generic Collections
Generics is the way of writing data structures without specifying type.
Data structures may be Classes, Structures, Interfaces, Methods and Delegates.
The predefined generic classes available in the namespace System.Collections.Generic

Advantages of using Generic Classes
Type Safe
Improved Performance
Reusable

Type Safe
The .Net languages like C#.Net, C++.Net and VB.NET are called as Strongly Typed languages or Type Safe Languages.
The Compiler checks for the Type conflict error and reports it during the compile time.
Weakly Typed languages like C++ does not check for type conflicts during compile time.
Strongly Typed Languages will lack the type safe when we use the Collection classes

CLR work during run time
During runtime the CLR creates separate classes for each parameterized type of generic class.
That’s why the type casting are not required to access the data of the instances.
The Generic class code acts as template for CLR to create separate classes.

Inheritance in Generics
Generic classes can be derived from an another Generic class
EX:
public class MyClass2 : MyClass2

Conclusion
Generics in .NET 2.0 are very powerful.
They allow you to write code without committing to a particular type, yet your code can enjoy type safety.
Generics are implemented in such a way as to provide good performance and avoid code bloat.

No comments:

Post a Comment