2

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?

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. You are right, new() is too strict. At now it seems that throwing an exception in run-time is a good solution. But I will think about creating parameterless constructors for my types because to have compile-time checks is better for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.