4

I can do this:

void MyMethod<T>() where T : class { } 

Is there anything like this?

void MyMethod<T>() where T : interface { } 

I'd prefer not to specify the interface name explicitly.

The alternative is that I can pass in an argument that's constrained by class and throw an exception if typeof(T).IsInterface returns false, but that's not as clean as a constraint.

3
  • 2
    This sounds like a solution to an XY Problem - could you show more about what you're trying to solve by wanting to do this? Commented Jan 20, 2016 at 15:26
  • 1
    What's the purpose of such a constraint? Commented Jan 20, 2016 at 15:26
  • Possible duplicate of How can I use interface as a C# generic type constraint? Commented Apr 23, 2017 at 11:16

1 Answer 1

1

This makes no sense since it doesn't leads to any limitations.

Constraint class means that the type argument must be a reference type.

So what interface without explicit interface name should limit?

Interface itself is just a declaration of methods/properties, so constraint "something is interface" literally mean "something has some declarations" - that is useless.

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

9 Comments

You know what, you're right. There can be no instance of an interface, so nothing will ever be passed in that is only an interface. If only I could delete this question.
All interface types must be reference types.
Answer is wrong: it would limit T to be an interface type. So MyMethod<IDisposable>() or MyMethod<IEnumerable<string>> would work fine, whereas MyMethod<string>()would not work. OP is right, this constraint does not exist in C# right now. But the real question is: would such a feature be really useful? I can't think of a use case.
@oscilatingcretin: another use case that frequently arises is when you are using some IoC (for instance Autofac). In that case, you will often call scope.Resolve<IMyContract>() and get some instance implementing IMyContract without knowing what is the concrete type of the instance you receive. And most of the time, you just don't care.
@Falanwe I second, it is an incorrect answer. There're even real cases where it is necessary. For example if you want to proxy an instance implementing certain interface - with interface type as T you can be certain that you can proxy everything just fine. But if someone provides sealed class there or class with non-virtual methods - the code will fail miserably at runtime.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.