Search code examples
.netgenericsanonymous-methods

Create anonymous function using generic type parameters?


Let's say I have this method:

int MyMethod(int arg)
{
    return arg;
}

I can create an anonymous equivalent of that like this:

Func<int, int> MyAnonMethod = (arg) =>
{
    return arg;
};

But let's say I have a method that uses generic type parameters like this:

T MyMethod<T>(T arg)
{
    return arg;
}

How can I create that as an anonymous method?


Solution

  • You have two choices:

    1. You create a concrete delegate object, one that specifies the type of T
    2. You declare the delegate in a generic context, using an existing T.

    Example of the first

    var f = new Func<int, int>(MyMethod<int>);
    var result = f(10);
    

    Example of the second

    T Test<T>()
    {
        T arg = default(T);
        Func<T, T> func = MyMethod; // Generic delegate
        return func(arg);
    }
    
    // Define other methods and classes here
    T MyMethod<T>(T arg)
    {
        return arg;
    }
    

    You will not be able to persuade the compiler or intellisense to carry the generic T with the delegate in a non-generic context and then work out the actual T when calling it.

    So this is not legal:

    void Test()
    {
        var fn = new Func<T, T>(MyMethod<T>);
        fn(10); // returns 10
        fn("Test"); // returns "Test"
    }