Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

generic function where generic type is any interface

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; }
like image 578
Greg Bogumil Avatar asked Sep 15 '26 10:09

Greg Bogumil


2 Answers

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

    // ...
}
like image 88
Reed Copsey Avatar answered Sep 16 '26 22:09

Reed Copsey


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

like image 21
Adam Robinson Avatar answered Sep 17 '26 00:09

Adam Robinson