There are two type of generic :
one = generic method
two = generic class
For example :
using System;
class Test<T>
{
T _value;
public Test(T t)
{
// The field has the same type as the parameter.
this._value = t;
}
public void Write()
{
Console.WriteLine(this._value);
}
}
class Program
{
static void Main()
{
// Use the generic type Test with an int type parameter.
Test<int> test1 = new Test<int>(5);
// Call the Write method.
test1.Write();
// Use the generic type Test with a string type parameter.
Test<string> test2 = new Test<string>("cat");
test2.Write();
}
}
And you can set a constraints
in generic class.
For example
using System;
using System.Data;
/// <summary>
/// Requires type parameter that implements interface IEnumerable.
/// </summary>
class Ruby<T> where T : IDisposable
{
}
/// <summary>
/// Requires type parameter that is a struct.
/// </summary>
class Python<T> where T : struct
{
}
/// <summary>
/// Requires type parameter that is a reference type with a constructor.
/// </summary>
class Perl<V> where V : class, new()
{
}
class Program
{
static void Main()
{
// DataTable implements IDisposable so it can be used with Ruby.
Ruby<DataTable> ruby = new Ruby<DataTable>();
// Int is a struct (ValueType) so it can be used with Python.
Python<int> python = new Python<int>();
// Program is a class with a parameterless constructor (implicit)
// ... so it can be used with Perl.
Perl<Program> perl = new Perl<Program>();
}
}
And for generic method
using System;
using System.Collections.Generic;
class Program
{
static List<T> GetInitializedList<T>(T value, int count)
{
// This generic method returns a List with ten elements initialized.
// ... It uses a type parameter.
// ... It uses the "open type" T.
List<T> list = new List<T>();
for (int i = 0; i < count; i++)
{
list.Add(value);
}
return list;
}
static void Main()
{
// Use the generic method.
// ... Specifying the type parameter is optional here.
// ... Then print the results.
List<bool> list1 = GetInitializedList(true, 5);
List<string> list2 = GetInitializedList<string>("Perls", 3);
foreach (bool value in list1)
{
Console.WriteLine(value);
}
foreach (string value in list2)
{
Console.WriteLine(value);
}
}
}
Resource Of my answer are these link. C# Generic Class Generic Method