articles

Home / DeveloperSection / Articles / Using Generics in C#

Using Generics in C#

Anupam Mishra5983 22-Dec-2015
Introduction:

In C#, Generics are allow to you write a class or method that can work with any data type. If you want to delay specification of data type in a class or method, used generics. Generics is also provide a type safe code and re usability in the program. In a class different things are depend upon in data types just like constructor, methods, and delegate function etc. It is most commonly used in collection classes.

Benefits:

Suppose you are writing a program for Addition class that has to be two methods one is add a number and second one is display this addition. For a movement forgive about generics, let’s think about what will be scenario:

1.      Define classes for each data types: If you are using this approach then you will write redundant code for each one as well as discouraging code re usability.

2.      Defined class for data type as object: If you are using this approach then your performance would be degraded because of boxing and un-boxing are performed simultaneously.it would be lost type safety.

So, you are only one better option for that to use generic.it provided to us for that we are delaying declaration of data type and re usability as well as performance is fast of our program.    By creating a generic class, you can create a collection that is type-safe at compile-time. 

Generic Classes:

The System.Collection.Generic namespace also defines a number of classes that implement many of these key interfaces.

The Generic class defined by putting the <T> sign after the class name. It is not mandatory sign should a letter ‘T’ .you can use any alphabet letter, as you wish.

For example we define ‘Demo’ class as generic class as follows:

public class Demo<T> { }

 Constraints of Type Parameter:

As you know you are free for using any data types with generic classes.sometimeswe need to restrict the data types which can be used with particular generic class or methods. So this thing done via constraints .Some Constraints are as follows:

1.    Derivation Constraints: You can restrict the generic type parameter to be derivation of specified by any interface or class.For example,

public class Demo<T>where K: IComparable
// data type k is must implement IComparable Interface

2.   Constructor Constraints:  You can restrict to the generic type parameter to define default Constructor.

Class Demo<K,T> where T:new()// T must have a default constructor
{
      Public Demo(){  }
}
Public class Demo1<K,T> where K: Incomparable<K>,new()
// K must implement Icomparable <K> and have default constructor

Reference/Value Type Constraints: You will need some time to define generic datatype is value type or referenced type.For example Structure or Class.

For structure:

Public class Demo where

T: struct {}
For Class:
Public class Demo where
T: class {}
In Inheritence:
Public class ChildClass<T>:ParentClass<T>where

T:IComparable
//ChildClass and ParentClass will have generic type and T
must implemented IComparable Interface
Generic Interface and Generic Abstract Class:

You can define generic interfaces, generic abstract classes, and even generic abstract methods. These types behave like any other generic base type:

 

public interface InterfaceDemo<T>
{
   T  DemoMethod(T t);
}
public abstract class BaseClass<T>
{
   public abstract T BaseMethod(T t);
}
Generic Methods:
You can define generic methods. As follows:

 

public class DemoClass<T>
{
   public void DemoMethod<X>(X x)
   {...}
}

     Using Generics in static method:

 static void Swap<T>(ref T a, ref Tb)
     {    
         T temp;
         temp = a;
         a = b;
         b = temp;
    }
  

Generics Delegate:

A delegate defined in a class can take advantage of the generic type parameter of


that class. For example:

 

public class MyClass<T>
{
   public delegate void GenericDelegate(T t);
   public void MyMethod(T t)
   {...}
}

For example, we have define one interface and declared one class that implement interface as generic type.For checking with different data types in generic class and constructor.

using System;
using System.Collections.Generic;
//Defining interface
publicinterfaceMyInterface
{
     void Show();
}
//Making generic class that is also implementing above interface
publicclassDemo<T>:MyInterface
{
    //parameterized constructor
    public Demo(T t)
    {
        Console.WriteLine("You are in constructor in Demo class and parameter is: "+t);
    }
    //given body to an interface method
    publicvoid Show()
    {
        Console.WriteLine("You are in Demo class that override My interface Show() method ");
    }
   }
classGenericDemo
{
      //main method
    staticvoid Main(string[] args)
    {
        Console.WriteLine(@"## Lets us try to use of Generics in a program.");
        Console.WriteLine();
        //Using as string type
        Demo<String> demo=newDemo<String>("Hi Everyone");
        demo.Show();
        Console.WriteLine();
       //Using as a int type
        Demo<int> demo1 = newDemo<int>(10000);
        demo1.Show();
        Console.WriteLine();
        //Using as a double type
        Demo<double> demo2 = newDemo<double>(10000.2220);
        demo2.Show();
        Console.WriteLine();
        Console.ReadKey();
    }
}
Output:


Using Generics in C#

 


Updated 07-Sep-2019

Leave Comment

Comments

Liked By