Alex Rivera | Logout

Passing around member functions in C#

Asked 2010-11-15T20:37:49.393
19

Mostly it comes handy that C# delegates already store the object together with the member function. But is there a way, to store -- and pass as parameters -- only the member function itself, just as the good old pointer-to-member-function in C++?

In case the description is less than clear, I give a self-contained example. And, yes, in the example the insistence to pass around member functions is totally pointless, but I have more serious uses for this.

class Foo {
    public int i { get; set; }
    /* Can this be done?
    public static int Apply (Foo obj, ???? method, int j) {
        return obj.method (j);
    }
    */
    public static int ApplyHack (Foo obj, Func<int, int> method, int j) {
        return (int) method.Method.Invoke (obj, new object [] { j });
    }
    public static readonly Foo _ = new Foo (); // dummy object for ApplyHack

    public int Multiply (int j) {
        return i * j;
    }
    public int Add (int j) {
        return i + j;
    }
}
class Program {
    static void Main (string [] args) {
        var foo = new Foo { i = 7 };
        Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Multiply, 5));
        Console.Write ("{0}\n", Foo.ApplyHack (foo, Foo._.Add, 5));
        Console.ReadKey ();
    }
}

You see, the only workaround I've found is rather ugly and probably slow.

c#
Edit
Report

1 Answer

2

You could retrieve and reuse the MethodInfo for the method or just use the name and extract the method at runtime.

 public static int ApplyHack (Foo obj, string methodName, int j)
 {
    var method = typeof(Foo).GetMethod(methodName);   
    return (int) method.Invoke (obj, new object [] { j });    
 }

I'd be very careful that this was actually necessary as it seems like a code smell to me.

answered 2010-11-15T20:41:30.473

Your Answer