oscilatingcretin
oscilatingcretin

Reputation: 10959

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?

Upvotes: 0

Views: 897

Answers (3)

Amit
Amit

Reputation: 46361

All concrete methods from generics are anonymous. You can't have it the other way around.

It's simple to do that:

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

//...

Func<int, int> MyAnonMethod = MyMethod<int>;
MyAnonMethod(1); // returns 1

If MyMethod is used directly, it will implicitly use a proper type, for example:

MyMethod(1); // returns 1 of type int

Upvotes: 0

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391664

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"
}

Upvotes: 2

Patrick Huizinga
Patrick Huizinga

Reputation: 1340

you can use

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

if you're at a spot (method, class) where you have a T. If you don't have a T you could create a method that returns a Func like:

Func<T, T> CreateMyAnonMethod()
{
    returns (arg) => { return arg; };
}

Upvotes: 0

Related Questions