Generics are intended to maximize code reuse and maintain type safety. Generics are useful where similar methods are applicable to different classes but you want to be clear in development of API's what the different classes are. Generics do this by eliminating the need for type casting when developing code for algorithms that could be used to process many different types of objects. Potentially expensive boxing and unboxing operations that are implicitly constructed by the C# compiler when type conversion is needed can be avoided with generics. C# generics are similar to C++ templates and Java generics with a few differences.
Here is an example of a generic class for sequence data. The class could be used for DNA, RNA, or amino acid sequences but it is still specific from a client code perspective, which type of sequence it applies to.
The class T. When it is used to
declared and instantiate variable sequence in SequenceTest the concrete class
DNASymbol is used. It is then a compile error to use anything except a DNASymbol
in the
Generic types can also be declared with interfaces, class methods, and delegates. Generic types in delegates can be particularly useful in processing events without the need to type cast the event source and arguments.
One of the differences of C# generics with C++ templates and Java generics is that in C# it is possible to place restrictions on the type parameters. The type parameter can be restricted to either a value type, a reference type, to be derived from a specific base class, implement a specific interface, or have a zero argument constructor. See the C# Programming Guide for details.
Generics are most frequently used with collections. Version 2 of the .NET Framework has a number of collections classes in the System.Collections.Generic namespace that use generics.
There are no user comments.
Please send ideas and opinions by email at alexamies@gmail.com.