Mega Code Archive

 
Categories / C# Book / 01 Language Basics
 

0180 Generic type parameter constraints

We can add constraints to generic type parameters with the following syntax. where: constraint The constraints can be the follows: Constraint Meaning where T : base-class Base class constraint where T : interface Interface constraint where T : class Reference-type constraint where T : struct Value-type constraint where T : new() Parameterless constructor constraint where U : T Naked type constraint using System; class Shape{ } class Rectangle: Shape{ } class Circle: Shape{ } class GenericClass<T> where T : Shape{ } class Test { static void Main() { GenericClass<Rectangle> g = new GenericClass<Rectangle>(); } } interface constraint using System; interface PrintTable{ void print(); } class Rectangle : PrintTable { } class GenericClass<T> where T : PrintTable { } class Test { static void Main() { GenericClass<Rectangle> g = new GenericClass<Rectangle>(); } }