odiseh
odiseh

Reputation: 26517

.net: How to enforce some limitations on Generics?

Is it possible enforcing some limitations on Type T in Generics?

Upvotes: 1

Views: 228

Answers (3)

Tim Barrass
Tim Barrass

Reputation: 4939

Basically

public class MyClass<T> where T : ISomeInterface

for example. Lots of existing SO questions too, like this one for extra detail.

Upvotes: 3

nan
nan

Reputation: 20296

Yes, you can put some constraints on T. The constraints are introduced with where clause. Check here

where T: struct

The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.

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 : <base class name>

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

where T : <interface name>

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

where T : U

The type argument supplied for T must be or derive from the argument supplied for U.

Upvotes: 4

Tim Lloyd
Tim Lloyd

Reputation: 38434

Please see generic parameter constraints. When creating your own generic types and methods, constraints allow you to apply some rules concerning the type parameters e.g. that they support required interfaces or have a default constructor.

Upvotes: 2

Related Questions