Level 6 — Generics and Delegates
Generic constraints
Original notes by SunDiaL · View English source
You can restrict what types a generic can be by using constraints. Common constraints include:
where T : class– T must be a reference typewhere T : struct– T must be a value typewhere T : new()– T must have a public parameterless constructorwhere T : BaseClass– T must inherit from a specific base classwhere T : Interface– T must implement a specific interfacewhere T : unmanaged– T must be an unmanaged type (likeint,float, etc.)
Example
public class Printer<T> where T : class
{
public void Print(T item)
{
if (item == null)
{
Console.WriteLine("Nothing to print.");
return;
}
Console.WriteLine(item.ToString());
}
}
public void Main()
{
Printer<string> p1 = new Printer<string>();
p1.Print("Hello"); // prints "Hello"
p1.Print(null); // prints "Nothing to print"
Printer<int> p2 = new Printer<int>(); // compile-time error: int is not a class
}