Skip to main content

.NET Generic Constraints Syntax

Generic supports four types of constraints:
  1. Interface: Allow only types that implement specific interfaces to use your generic
  2. Base class: Allow only types that is or inherited form specific base class to use your generic
  3. Constructor: Allow only types that implement specific constructors to use your generic
  4. Reference or value type: Limit the types to use your generic either reference type or value type
Examples for these constraints:

Interface: T must implement IComparable interface
public class MyGenericClass where T: IComparable

Base class: T must be or inherited from MyBaseClass
public class MyGenericClass where T: MyBaseClass

Constructor: T must have at least the default constructor available
public class MyGenericClass where T: new ()

Reference or value type: T must be a reference type
public class MyGenericClass where T: class

Reference or value type: T must be a value type
public class MyGenericClass where T: struct

Comments