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?
You have two choices:
T
T
.var f = new Func<int, int>(MyMethod<int>);
var result = f(10);
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"
}