Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put an interface constraint on a generic method in C# 3.5?

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?

like image 967
andrecarlucci Avatar asked Jul 09 '09 14:07

andrecarlucci


1 Answers

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
like image 143
LBushkin Avatar answered Nov 15 '22 06:11

LBushkin