Tuesday, August 16, 2011

Generic Constraints Situations

Here paste a form:

onstraint

Description

where T: struct

The type argument must be a value type. Any value type except Nullable can be specified.

where T : class

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

where T : new()

The type argument must have a public parameterless constructor. When used together with other constraints, the new() constraint must be specified last.

where T : Baseclass

The type argument must be or derive from the specified base class.

where T : Iinterfacename

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.


Let's take the constructor constraints as an example:

where T: new(), this means when we instantiate T, we limit the class constructor doesn't have parameter,

and where T: new(int,string), Then when we instantiate T, we can only write T t=new T(3, "string") like this.

No comments: