Home > DeveloperSection > Blogs > Why Generics in C#

Why Generics in C#


C# C# 
Ratings:
0 Comment(s)
 1756  View(s)
Rate this:

Why Generics in C#

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);

   }

}


Don't want to miss updates? Please click the below button!

Follow MindStick