Generics

Generics is one of the features of C#, It allows us to define type-safe classes, methods, interfaces,
delegates, and events. It helps in improving the code reusability and performance.

This helps in having a single method which can take different data types as int or double or string or bool,
etc... instead of having multiple overloading methods for a specific scenario.

Syntax:

//Generic Class
Class MySample
{
}
//Creating an instance to class by specifying the type at T.
MySample obj = new MySample();
//Generic Array
T[] array = new T[20]

Example:

 

using System;
namespace SampleProgram {
  class MySample {
    public static void Main(string[] args) {
      //Create instance to class with int type so it takes int param.
      MyPrintClass <
      int >
      objInt = new MyPrintClass <
      int >
      ();
      objInt.Input = 145;
      objInt.PrintHere(238);
      //Create instance to same class with string type
      MyPrintClass <
      string >
      objString = new MyPrintClass <
      string >
      ();
      objString.Input = "
      Input ";
      objString.PrintHere(" Hello");
    }
  }
  class MyPrintClass <
  T >{
    public T Input {
      get;
      set;
    }
    public void PrintHere(T data) {
      Console.WriteLine( " Input is: " + Input);
      Console.WriteLine( " Prints the Type and Value Here: ");
      switch (Type.GetTypeCode(data.GetType())) {
      case TypeCode.Int32:
      case TypeCode.Int64:
        Console.WriteLine(" Integer Type, Value is " + data);
        break;
      case TypeCode.Double:
        Console.WriteLine( " Integer Type, Value is " + data);
        break;
      case TypeCode.String:
        Console.WriteLine( " String Type, Value is " + data);
        break;
      default:
        Console.WriteLine( "
      default, this type not exists ");
        break;
      }
    }
  }
}

 

The output will be:

Input is: 145
Prints the Type and Value Here:
Integer Type, Value is 238
Input is: Input
Prints the Type and Value Here:
String Type, Value is Hello

 

 

Related Tutorials