views:

311

answers:

3

I want to achieve something like this in C# 3.5:

public void Register<T>() : where T : interface {}

I can do it with class or struct, but how to do it with an interface?

Thanks!

André

+3  A: 

C# and the CLR don't support overall interface constraints, although you can constrain it to a particular interface (see other answers). The closest you can get is 'class' and check the type using reflection at runtime I'm afraid. Why would you want an interface constraint in the first place?

thecoop
+2  A: 

If you are asking about adding a constraint to a specific interface, that's straightforward:

public void Register<T>( T data ) where T : ISomeInterface

If you are asking whether a keyword exists like class or struct to constrain the range of possible types for T, that is not available.

While you can write:

public void Register<T>( T data ) where T : class // (or struct)

you cannot write:

public void Register<T>( T data ) where T : interface
LBushkin
A: 

You can't demand that T is an interface, so you'd have to use reflection at runtime to assert this.

Matt Howells