Type constraints (class and struct) C# with Example



Type constraints (class and struct) C# with Example

It is possible to specify whether or not the type argument should be a reference type or a value type by using the 
respective constraints class or struct. If these constraints are used, they must be defined before all other 
constraints (for example a parent type or new()) can be listed. 
// TRef must be a reference type, the use of Int32, Single, etc. is invalid. 
// Interfaces are valid, as they are reference types 
class AcceptsRefType 
where TRef : class 
{ 
// TStruct must be a value type. 
public void AcceptStruct() 
where TStruct : struct 
{ 
} 
// If multiple constraints are used along with class/struct 
// then the class or struct constraint MUST be specified first 
public void Foo() 
where TComparableClass : class, IComparable 
{ 
} 
} 

0 Comment's

Comment Form