The topics described here concentrates fully on pure .Net Framework, describing actual meaning of some programming concepts, FCL and best practices. However you will be using these concepts in all . Net framework compatible languages like Microsoft visual basic .net (VB.Net) or C# .Net (csharp.Net) to build a web application (Asp.Net) or Desktop applications (winforms .net) or Web/Windows services





This blog has moved!

You will be automatically redirected to the new address. If that does not occur, visit
http://Codemine.net
and update your bookmarks.

Friday, July 13, 2007

Generics in .Net

Generics is another mechanism offered by the common language runtime (CLR) and programming languages that provides one more form of code re-use: algorithm re-use.
Basically it is a template like algorithm, procedure or object which doesn't specify what data type it operates on. And later on while instantiating or using this object or procedure we can pass in the actual type we need as type parameter in to this already defined chunk. This can be generically applied to objects of any type.This functionslity is almost similar to template classes in C++ and Generics in Java.

We can use generics for both reference types as well as value types, but it does not allow the creation of generic enumerated types. Also the CLR allows the creation of generic interfaces and generic delegates.
We can make a class generic by placing the immediately after the class name and at this time the data type of is unspecified. And here is called as the type parameters. It is possible to send more than one type parameter to a generic class.

Generics provide the following big benefits to developers:

Source code protection :
The developer using a generic algorithm doesn't need to have
access to the algorithm's source code.
When a generic algorithm is used with a specific type, the compiler and the CLR understand this and ensure that only objects compatible with the specified data type are used with the algorithm. Attempting to use an object of an incompatible type will result in either a compiler error or a run-time exception being thrown. So for this we use generic constraints ,which says that if you want to use me, you have to be this type, inherit this type or implement this interface to call or instantiate this generic algorithm. We implement this using the where clause.

Cleaner Code:
Since the compiler enforces type safety, fewer casts are required in your source code, meaning that your code is easier to write and maintain.

• Better Performance:
Before generics, the way to define a generalized algorithm was to define all of its members to work with the Object data type. If you wanted to use the algorithm with value type instances, the CLR had to box the value type instance prior to calling the members of the algorithm and this ignites frequent garbage collections.

0 comments: