views:

93

answers:

3

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; }
+5  A: 

No, there's no way to constrain the type to interfaces only.

Adam Robinson
+6  A: 

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");

    // ...
}
Reed Copsey
excellent. Thank you.
gbogumil
+1  A: 

You have to use a specific interface. You could create a base interface that all your other interfaces derive from and use that as the constraint.

Seattle Leonard