Saturday, 25 October 2008

Generic Constraints

ConstraintMeaning in Life
where T : structThe type parameter <T> must have System.ValueType in its chain of inheritance.
where T : classThe type parameter <T> must not have System.ValueType in its chain of inheritance (e.g., <T> must be a reference type).
where T : new()The type parameter <T> must have a default constructor. This is very helpful if your generic type must create an instance of the type parameter, as you cannot assume the format of custom constructors. Note that this constraint must be listed last on a multiconstrained type.
where T : NameOfBaseClassThe type parameter <T> must be derived from the class specified by NameOfBaseClass.
where T : NameOfInterfaceThe type parameter <T> must implement the interface specified by NameOfInterface.

The syntax for defining both inheritance and constraints is:

class FSM : AbstractFSM, INotifyPropertyChanged
where TState : struct
where TEvent : struct

To define multiple constraints for a single type parameter separate them with commas. It seems like "new()" has to be the last in the list.

private void CollectionConstructorTest()
where TVCollection : VCollection, new()
where TVClass : VClass, new()

1 comment:

MrTidy OTR said...

Nice - thanks for taking the time to write out the info.