Friday, July 22, 2005

Generics in .NET Framework 2.0

Generics are now part of .NET Framework 2.0. Those who have used C++ would be aware of templates. Generics are very similar to it.
Earlier in .NET 1.1 when you created collections the objects contained within these collections could be anything and supposing you intention was to have only integers but if you added a string it would not have been detected until runtime. But in using generics you can strong type the values in the collection hence any type mismatch would be detected at compile time.
The difference between templates and generics is that the compiled code with generics would still contain the generics as it is without it being expanded to its types and only later at runtime this is expanded. This is primarily to avoid code bloat.
You can use the generics provided with the .NET framework 2.0 or create your own generics. To create your own generics is simple.

1. Create the generic class.

public class MyOptions<T>
{
// Add any class processing information
}

2. Now use the class

MyOptions<int> values = new MyOptions<int>();
MyOptions<string> names = new MyOptions<string>();


The T within the angle bracket mentions the actual type that will be used when the class is instantiated as shown in step 2.
Remember every time when you do this
MyOptions<int> values = new MyOptions<int>(); it actually instantiates a new class that would accept only the type mentioned. Here it's integers only.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home