Generics In .NET Framework

What is the Concept Behind Generics ?

In .NET framework while coding we may come across sometimes where we want a particular method to behave differently depending on our requirements. Lets say we have a method ShowResults which performs some task depending on our inputs on a certain data types. lets say it can accept only string variables to do a job or only integers or only objects. But we can make this method a generic one which can accept an argument in a generic manner irrespective of the data type of the argument.

This means that by using a generic type parameter T, you can write a single class MyClass<T> and then you can use it as MyClass<int>, MyClass<string> or MyClass<MyClass> without any risk of run-time casts or boxing operations.

This Generics in .NET Framework is very much similar to Templates in C++

.NET Framework introduces a new namespace viz. System.Collections.Generic for using this Generics.

Explanation on ASP.NET Generics


We will see here the 2 types of Generics those we can use in .NET Framework.
  • Generic Classes
  • Generic Methods

Generic Classes

           Generic Classes operates not upon a perticular data types rather in a generic manner. The best example will be stack, queues, linked lists and all the data structures those performs data in and out oeration without paying any attentions towards the datatypes.

 public class Generic <T>
    {
        T name;
        T country;
    }
Here <T> represents the generic datatype of the class, and you can insantiate the class like below;
   public static void Main()
        {
            Generic<string> g = new Generic<string>();
            g.name = "Tapan";
            g.country= "India";           
        }
As all of you see here we are using the Generic class has its data type string that is "T" represents string and the members "name", "country" accepts string values. You can replace the string with int also and with char also. 

Generic Methods

 This generic methods are also same as the classes. Herer in Generic methods are declaired with a type parameter. Lets see the below example

void Add( ref T left, ref T right)
    {
        T temp;
        temp = left + right;
    }
Now see how to call this Add method.
void Add( ref T left, ref T right)
    {
        T temp;
        temp = left + right;
    }
You can also ommit the parameter <int> while calling the Add() method, and the .NET compiler will guess it for you.

Thats all, hopefully you got something fundamentals regarding generics in .NET Frameworks in this article.

Happy Coding...

No comments:

Post a Comment