Many developers face problems with type safety when working in .Net environment because .In C++ class templates were used which allows a programmer to create a class generically so that it will increase the reusability and then to instantiate that class with type-specification so that to have type safety.
In .Net 1.x since every type was derived from the class Object so when ever you use collections there was no type checking at all and the problem usually creates headaches on the runtime.
Generics will allow a programmer to solve the type safety problem at compile time.
For e.g. in C# 1.1 when using push and pop operations of a stack let say for integers we used to write:
Stack intstack = new Stack();
Intstack.Push(10);
Int ipop=(int)stack.Pop();
In the above example when the value of an integer is pushed it is automatically boxed but when it is poped we had to explicitly unbox it.
Now see another problem when we write:
Stack intstack = new Stack();
Intstack.Push(10);
string spop=(string)stack.Pop();
The above code will not give compile time error but we know it will cause problems for us.
Now Microsoft in their .Net 2.0 environment has solved this problem, now we can use generics and some incorrect retrieve (such as Pop ()) operation with respect to type safety is performed the compiler will give a type mismatch error.
For e.g. look at the following code:
Intstack<int> istack= new Intstack<int>();
Istack.Insert(new int());
Int I = istack.Retrieve();
Istack.Insert(“ faisal “); // Now the compiler will give type mismatch error
Declaration of Intstack class can be done as follows:
Public class Intstack<T>
{
T[ ] elements;
int numelements;
public void Insert(T elements)
{
//do something
}
public T Retrieve()
{
// do something
}
}
I hope this article would have given you some idea one of the many new features in the .Net environment which will help you to improve your product quality.
The above article was written by one of my BEST friend Syed Faisal Rehman… I really liked this new .NET feature as im a big fan of C++ and love to code C++….now since every thing is changing and with .NET microsoft has brought revolution so me myself switched to .net though i didnt want but what shuld i do its market requirement