dotsquid
dotsquid

Reputation: 73

C#: passing a method with variable parameters as parameter of another method

So here I'm trying to pass a method with a random signature to Foo method. But without any luck.
The thing is that I can pass any action. But on a method.
Any help?

class Bar
{
    void M1(int a) { }
    void M2(string a, int b) { }

    Action<string, int, bool> A1 = (s, i, b) => {};
    Action<int, float> A2 = (i, f) => {};

    void Foo(Delegate f) {}

    void Test()
    {
        Foo(A1);
        Foo(A2);
        // Foo(M1); // nope
        // Foo(M2); // no way
    }
}

PS. I'm trying to get this working under Unity3d's Mono.

Upvotes: 2

Views: 142

Answers (1)

Evk
Evk

Reputation: 101443

You have to cast to concrete delegate type to do that, like this:

void Test()
{
    Foo(A1);
    Foo(A2);
    Foo((Action<int>) M1);
    Foo((Action<string, int>)M2); 
}

The reason for this is M1 and M2 are what is called method groups. That just means they refer to one or more methods. Why it can be more than one? Because you might have multiple methods with name M1, each of which accepts different set of arguments. But, even if you have just one overload, like in your case, there might be multiple delegate types compatible with that overload signature (that might be Action<int> or YourDelegateType which is declared as delegate void YourDelegateType(int arg), or whatever else).

That is why there is no implicit conversion from method group to delegate, and you have to cast method group to specific delegate type explicitly.

Upvotes: 4

Related Questions