Maxim
Maxim

Reputation: 2128

Constrain C# generic parameter with interface implementations

To illustrate my question I've written a simple method:

public static T ConvertTo<T>(...)
    where T : ISomeInterface
{
    // return an instance of T
}

Obviously this method can be called like

ConvertTo<ISomeInterface>(...)

But in my case it doesn't make sense. Method should return an instance of a class that implements ISomeInterface. At now I throw NotSupportedException for any type the method unable to work with and I satisfied with this solution. But if I could filter out an interface itself in compile time it would be better.

So my question is: Is it possible to constrain generic parameter with implementations of an interface?

Upvotes: 2

Views: 100

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156938

So my question is: Is it possible to constrain generic parameter with implementations of an interface?

No, there is not. You have found the best-fitting solutions: class and new(), where class only filters out structs, etc. class and new() used together is the only real solution, but a solution that is actually too strict.

You might have some luck with code analyzers or AOP where can filter out bad calls on compile-time.

Upvotes: 2

Related Questions