Wednesday, June 30, 2010

What is Generics in C#?

1. Generics allow you to define type-safe data structures, without committing to actual data types.
2. Result higher quality of code by reuse data processing algorithm without duplicating type-specific code.
3. Generics allow you to define type-safe classes without compromising type safety, performance, or productivity.

Example:
.Net 1.1 way of implementing Stack data structure providing Push() and Pop() methods.
For general purpose of Stack, it used to store instances of various type. Old way using Object-based stack, which is amorphous object. This is because Object is canonical .NET base type, it able to hold any type of items.

Problem:
1. Performance in boxing and unboxing value types when pushing and popping process.
2. Type safety. Compiler allow anything cast from Object type. Hence, programmer losing compile-time type safety. Cast wrongly will raise an invalid cast exception at run time.

Hence, to solve this, old way is to create type-specific Stack data structure. For Interger, using InsStack, for String, use StringStack.

Writing type-specific data structures is a tedious, repetitive, and error-prone task.
In addition, there is no way to foresee the use of unknown or yet-undefined future types, so you have to keep an Object-based data structure as well.

Sample Code Download : Learn_Generics.zip

No comments:

Image Understanding (IU)

Throughout these years, the growth of digital media collections has been accelerating, particularly in still images. These artifacts repre...