0

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?

oscilatingcretin
  • 10,457
  • 39
  • 119
  • 206

3 Answers3

2

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"
}
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
0

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
Amit
  • 45,440
  • 9
  • 78
  • 110
  • But this implies that I know `T` which I don't. Just like I don't know `T` in my concrete method, I can't know `T` in my anonymous method. – oscilatingcretin Oct 13 '15 at 13:43
  • You mean that in `(arg) ...` you didn't specify `int`? is *that* what you're looking for? – Amit Oct 13 '15 at 13:45
  • Correct. I need to be able to pass in any type. When I call the anonymous method, I want the intellisense tooltip to show `T MyClass.MyMethod(T arg)`. Once I complete the expression as `int i = MyMethod(1)`, I then want intellisense tooltip to show `int MyClass.MyMethod(int arg)`. – oscilatingcretin Oct 13 '15 at 13:49
  • Not sure about IntelliSense, but `MyMethod(1)` will both accept and return an `int` (Notice, `MyMethod`, not `MyAnonMethod`. `int` is implicit). – Amit Oct 13 '15 at 13:51
0

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; };
}
Patrick Huizinga
  • 1,342
  • 11
  • 25