Using generic interface as typeparameter for a method or function

364 views Asked by At

Assuming the following interface which I use to define the parameter type and return type for a stored procedure...

public interface IStoredProcedure<out TReturn, out TParameter>
    where TReturn : class 
    where TParameter : class
{
    TReturn ReturnType { get; }

    TParameter ParameterType { get; }
}

...is it possible to pass this interface as a TypeParameter for a method? Something along the lines of this (which does not compile)

public static void DoAction<TProcedure>(TProcedure procedure1)
        where TProcedure : IStoredProcedure<TReturnType, TParameterType>
{
        // do some work
}

... or something along these lines...

public static void DoAction<IStoredProcedure<TReturnType, TParameterType>>(IStoredProcedure procedure1)
        where TReturnType : class
        where TParameterType : class
{
        // do some work
}

neither of these two methods compile, and I just cant work out how to write them to make them compile. In the DoAction() method I need to interogate the types of the parameters and return type.

2

There are 2 answers

3
Jon Skeet On BEST ANSWER

You need to use the type arguments where you specify the interface:

public static void DoAction<TReturnType, TParameterType>
   (IStoredProcedure<TReturnType, TParameterType> procedure1)
    where TReturnType : class
    where TParameterType : class
{
    // do some work
}

... otherwise you're referring to a non-generic IStoredProcedure interface. (Don't forget that C# allows types to be "overloaded" by generic arity.)

4
nickm On
public static void DoAction<TProcedure, TReturnType, TParameterType>(TProcedure procedure1)
        where TProcedure : IStoredProcedure<TReturnType, TParameterType>
        where TReturnType : class
        where TParameterType : class
        {
            // do some work
        }