Generics defer the determination of the type of a class or method until the class or method is instantiated, that is, the first declaration is not specifying a type, and then specifying the type when it is used (instantiated)
Generics can be used for classes, methods, delegates, events, and so on
Let's write a simple generic type
public class Genericclass<t>
{
void SomeMethod (T t)
{
Do something
}
}
Here's how to use it:
Instantiate a class
Genericclass<int> gci=new genericclass<int> (); method SomeMethod has an integer type parameter.
Write an example below
Using System;
Using System.Collections.Generic;
Using System.Text;
Namespace Example
{
class Genericclass<t>
{
public void Printtype (T t)
{
Console.WriteLine ("value:{0} Type:{1} ", T,t.gettype ());
}
}
Class program
{
static void Main (string[] args)
{
int i = 0;
genericclass<int> GCI = new Genericclass<int> ();
GCI. Printtype (i);
string s = "Hello";
genericclass<string> GCS = new genericclass<string> ();
Gcs. Printtype (s);
Console.ReadLine ();
}
}
}
A generic method can appear on a generic or non-generic type. It is important to note that the method is a generic method, not as long as the method belongs to a generic type, or even if the type of the method's formal parameter is a generic parameter of the enclosing type. A method can be called a generic method only if it has its own type parameter list. In the following code, only method G is a generic method.
Class A
{
T g<t> (t arg) {...}
}
Class generic<t>
{
T M (t arg) {...}
}
Where of generics
The where of generics can be qualified for type parameters. There are several ways to do this.
The where t:struct restriction type parameter T must inherit from System.ValueType.
The where T:class restriction type parameter T must be a reference type, that is, cannot inherit from System.ValueType.
where t:new () restriction type parameter T must have a default constructor
The where T:nameofclass restriction type parameter T must inherit from a class or implement an interface.
These limits can be combined, for example: public class point where T:class, IComparable, New ()
For example:
Class person<t> where T:class
{
}
Class Program
{
static void Main (string[] args)
{
person<int> BB = new person<int> (); Wrong,
Error 1 type ' int ' must be a reference type to be used as a parameter "T" in a generic type or method "Consoleapplication1.person<t>"
}
}
Generics in. Net