Generics
i want to use generics in my project...
how to use and what is the purpose of using generics .....is it just like arrays? what is the advantages and disadvantages
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Bechir BejaouiPosted Oct 27, 2008, 9:52 AM
Say that you design a Rectangle class
public class Rectangle
{
public Rectangle(int height, int width)
{
this.height = height;
this.width = width;
}
public int height { get; set; }
public int width { get; set; }
public override string ToString()
{
return string.Format("The height is {0} and the width is {1}", height, width);
}
}
You cloudn't define a new instance as bellow:
Rectangle Reg1 = new Rectangle(2.02, 2.05); since the height and width are type of integer you will recieve a compile error indicates that types aren't suitables
In the other hand, let's consider this class prototype
public class Rectangle
{
public Rectangle(T height, T width)
{
this.height = height;
this.width = width;
}
public T height { get; set; }
public T width { get; set; }
public override string ToString()
{
return string.Format("The height is {0} and the width is {1}", height, width);
}
}
The user could precise the type of height and width by him self as so
Rectangle
Rectangle
Rectangle
So there is no dependancy on a type you can precise the height and width type as you like
The generics are alomst used in lists and Ienumerable series