Generics in C #
Generics are the most useful C # 2.0 language extensions, beside Anonymous methods, Iterators, Partial types And Nullable types.What are generics? Generics permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate .Asty generics? To well knows Examine The Following Code: -
Public class stack {object [] Items; int count; public void push (object item) {...} public object pop () {...}}
We use the object type to store any type of data. The above simple Stack class stores its data in an object array, and its two methods, Push and Pop, use object to accept and return data. While the use of type object makes the Stack Class Very Flexible, IT IS Not without DrawBacks. For Example, IT IS Possible To Push A Value of Any Type, Such A Customer Instance, Onto A Stack.
However, WHEN a Value Is Retrieved, The Result of The Pop Method Must Explicitly Be Cast Back to the appropriate Type, Which I TEDIOS TO WRITE AND Carries a Performance Penalty For Run-Time Type Checking:
Stack stack = new stack (); stack.push (new customer ()); Customer C = (Customer) stack.pop ();
If a value of a value type, such as an int
Stack stack = new stack (); stack.push (3); int i = (int) stack.pop ();
Such boxing and unboxing operations add performance overhead since they involve dynamic memory allocations and run-time type checks.A further issue with the Stack class is that it is not possible to enforce the kind of data placed on a stack. Indeed, a Customer instance CAN Be Pushed ON A Stack and The Accidentally Cast It To The Wrong Type After It Is Retrieved: Stack Stack = New Stack (); STACK.PUSH (); string s = (string) stack.pop ();
While the code above is an improper use of the Stack class, the code is technically speaking correct and a compile-time error is not reported. The problem does not become apparent until the code is executed, at which point an InvalidCastException is thrown.With Generics Those Problems Are All Solved. How ??
Public Class Stack
When the generic class stack
Stack
The Stack
IT WAS A BREIF Introduction To Generics That Will Be Included In The Next Version of C # (V 2.0). Which is Available Now On Its Beta Version With Visual C # 2005 Express Edition Beta 1.