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?

0

3 Answers 3

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"
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

4 Comments

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.
You mean that in (arg) ... you didn't specify int? is that what you're looking for?
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>(T arg). Once I complete the expression as int i = MyMethod(1), I then want intellisense tooltip to show int MyClass.MyMethod<int>(int arg).
Not sure about IntelliSense, but MyMethod(1) will both accept and return an int (Notice, MyMethod, not MyAnonMethod. int is implicit).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.