I'd like do implement a generic function with the generic constraint that the Type passed in is an interface. Is this possible in C#? I have it working fine without the constraint, but the code will fail at runtime if it is not an interface, so I'd like to have the compile time checking.
public T MyFunction<T> where T : {any interface type} { return null; }
You can constrain the type to a specific interface, but not "any" arbitrary interface.
// This is allowable
public T MyFunction<T>() where T : IMyInterface { return null; }
This will let you pass any object which implements that specific interface.
Edit:
Given your goals, from the comments, I would personally probably just put in some runtime checking:
public IEnumerable<T> LoadInterfaceImplementations<T>()
{
Type type = typeof(T);
if (!type.IsInterface)
throw new ArgumentException("The type must be an Interface");
// ...
}
No, there's no way to constrain the type to interfaces only.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With