blog

Home / DeveloperSection / Blogs / Why Generics in C#

Why Generics in C#

AVADHESH PATEL3366 17-Jan-2013

In this blog I not tell you “What is generic class in C#?” you can read about generic from below link.

http://www.mindstick.com/Blog/165/Generic%20class%20in%20c

Here I tell you “Why Generic in C# !”. First see below code:

class mindstick
{
int nRegNo;
string sAddress;
}


1.    Whenever we define the class in C#, C++ or in Java, class can have several types of variables.

2.   How in this case if we create an object, object consist several variables of different types.

3.   Now we want to create multiple object of same class but every object will have different type of variable called collection.

4.   Here come boxing and unboxing.

Conclusion: need to take care about conversion before assigning the data.

Now the main purpose of the using generics, each object will have multiple variable of similar type. Now we can prevent boxing and unboxing.

If we apply generic on class then we can achieve static polymorphism.

class mindstick
{
int nRegNo;
string sAddress;
}

mindstick <int> ms1 = new mindstick<int>();

mindstick <string> ms2 = new mindstick<string>();

Now in above program, we have two objects belong to same class supporting different data type not in same.  

This type of an object is called “Generic Object” and its class known as “Generic Class”. See below example.

class mindstick<A>
{
   public A assign(A a1)
   {
                return a1;
   }
}
public class caller
{
   public static void Main()
   {
     mindstick <int> k1= new <int>();
     mindstick <string> k2= new <string>();           
     int t1 = int k1.assign(12); // No change to apply conversion
     Console.WriteLine(t1);
   }
}


Updated 18-Sep-2014
Avadhesh Kumar Patel District Project Manager - Aligarh 14 months work experience in Panchayati Raj Department Sector as District Project Manager & 12 months work experience in IT Sector as Software Engineer. :-)

Leave Comment

Comments

Liked By