Generics

 Generics are similar to “templates” in C++.
 A generic is designed to represent a particular data type, during an object life time or a method execution.
 Here, you can observe two types of generics. One is representing a data type during an object life time and another one is representing a data type during the method execution time.

Types of Generics:

 Generic Classes:
The generic represents a data type, during the object’s life time of the class.

 Generic Methods:
The generic represents a data type, during the method execution.

Definition of Generic Classes:
 A class that contains a data member of the “generic” type.
 This should specify the generic type name after the class name as follows:
class classname<generic type name>
{

}

Definition of Generic Methods:
 A method that contains an argument of the “generic” type.
 This should specify the generic type name after the method name as follows:
accessmodifier returntype methodname<generic type name>(arguments)
{

}
Advantage of Generic Classes:
 According to generic classes, when an instance is created, the required type of values could be stored as the data members.

Advantage of Generic Methods:

 According to generic methods, when you call a method, you can pass difference types of arguments to the same method, without overloading it.

Implementation of Generic Classes

 Class Definition with Generics:
class classname<T>
{
accessmodifier T datamembername;
}

 Object Construction:
classname<data type> objname = new classname<data type>;

Implementation of Generic Methods

 Method Definition with Generics:
accessmodifier returntype methodname<T>(T arg)
{

}
 Method Calling:
methodname(value);

Generic Classes

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace GenericsDemo
{
class Sample<T>
{
T n;
public void Set(T n)
{
this.n = n;
}
public void Print()
{
Console.WriteLine(n);
}
}

class Program
{
static void Main(string[] args)
{
Sample<int> s1 = new Sample<int>();
s1.Set(10);
s1.Print();
Sample<string> s2 = new Sample<string>();
s2.Set("hai");
s2.Print();
Console.Read();
}
}
}
generics

Generic Methods

namespace MethodGenericsDemo
{
class Sample
{
public void ReverseAndPrint<T>(T[] arr)
{
Array.Reverse(arr);
foreach (T item in arr)
Console.Write(item + ", ");
Console.WriteLine();
}
}

class Program
{
static void Main(string[] args)
{
int[] intArray = { 3, 5, 7, 9, 11 };
string[] stringArray = { "first", "second", "third" };
double[] doubleArray = { 3.567, 7.891, 2.345 };
Sample s = new Sample();
s.ReverseAndPrint<int>(intArray);
s.ReverseAndPrint<string>(stringArray);
s.ReverseAndPrint<double>(doubleArray);
Console.Read();
}
}
}
generics