Search code examples
c#delegates

Ways to achieve constraint for a T parameter in interface to specific delegate type


I know that since C#7.3, we can use T : Delegate constraint. Could we be more specific - constraint to specific method signature that our interface is relying on (I know code contracts etc arguments, but if we had to) Something along those lines?

public delegate int SummingDelegate(int a, int b);

public interface IRelyOn<T> where T : SummingDelegate
{
    int ConsumingSum(T summingMethod);
}

EDIT: My scenario was to enforce some type of necessary method signatures to be used by a class from an interface that can be mocked and tested.


Solution

  • Generics are unnecessary for this scenario, where delegates already represent any method with a matching parameter list and return type. Simply use the delegate directly:

    public delegate int SummingDelegate(int a, int b);
    
    public interface IRelyOn
    {
        int ConsumingSum(SummingDelegate summingMethod);
    }