Common function, where the common type is any interface

I would like to implement a universal function with a common constraint, which Type passed as an interface. Is this possible in C #? I work fine without restriction, but the code will not work at runtime if it is not an interface, so I would like to check the compilation time.

public T MyFunction<T> where T : {any interface type} { return null; }
+3
source share
3 answers

You can restrict a type to a specific interface, but not to any arbitrary interface.

// This is allowable
public T MyFunction<T>() where T : IMyInterface { return null; }

This will allow you to pass any object that implements this particular interface.


Edit:

Given your goals, from the comments, I personally will probably just run a check of execution:

public IEnumerable<T> LoadInterfaceImplementations<T>()
{
    Type type = typeof(T);
    if (!type.IsInterface)
        throw new ArgumentException("The type must be an Interface");

    // ...
}
+7
source

, .

+5

You must use a specific interface. You can create a basic interface from which all other interfaces flow, and use this as a limitation.

+1
source

Source: https://habr.com/ru/post/1750718/