Tuesday, December 6, 2011

Understanding Generic Types and Advantages of Generic Types in console application.

Generic types were introduced in version 2.0 of the .NET Framework, and make it possible to design classes, structures, interfaces, and methods that defer the specification of one or more types until client code declares and instantiates the class or method. For example, by using a generic type parameter, you can write a single class that other client code can use without the cost or risk of CLR casts or boxing operations.
Generic types are designated by the syntax ClassName (C#), where T represents a data type that the client code must specify when it uses the generic class.

Advantages of Generic Types:
Type safety. Generic types enforce compile-time type checking. Types that are based on System.Object accept any data type, and you must write code to check whether an input data type is acceptable. With generic types, the compiler can catch type mismatches before run time.

Performance. Generic types do not have to box and unbox data because each one is specialized for one data type. Operations that are based on System.Object must box input data types to convert them to System.Object and unbox data that is destined for output.
Code consolidation. The code in a generic type has to be defined only once. A set of type-specific versions of a type must replicate the same code in each version; the only difference between each version is the specific data type for that version. With generic types, the type-specific versions are all generated from the original generic type.
Code reuse. Code that does not depend on a particular data type can be reused with various data types if it is generic. You can often reuse it even with a data type that you did not originally predict.
Integrated development environment (IDE) support. When you use a constructed type that is declared from a generic type, the IDE can give you more support while you develop your code. For example, the Microsoft IntelliSense® technology can show you the type-specific options for an argument to a constructor or method.
Generic algorithms. Abstract algorithms that are type-independent are good candidates for generic types. For example, a generic procedure that sorts items by using the IComparable interface can be used with any data type that implements IComparable.

No comments:

Recent Posts