jdelator
jdelator

Reputation: 4251

Cleanest way to dynamically call a non static method from a non static class?

I am looking for the cleanest way. I am tempted to use delegates not sure though.

Upvotes: 0

Views: 506

Answers (2)

Simon Buchan
Simon Buchan

Reputation: 13245

Are you after something like this?

class A
{
    public int Value;
    public int Add(int a) { return a + Value; }
    public int Mul(int a) { return a * Value; }
}

class Program
{
    static void Main( string[] args )
    {
        A a = new A();
        a.Value = 10;
        Func<int, int> f;
        f = a.Add;
        Console.WriteLine("Add: {0}", f(5));
        f = a.Mul;
        Console.WriteLine("Mul: {0}", f(5));
    }
}

If you need the object it's called on to be unbound, like C++ member function pointers, I'm not sure that C# supports that. You can always use a lambda or delegate, though:

Func<A,int,int> f = delegate( A o, int i ) { return o.Add( i ); };
Console.WriteLine( "Add: {0}", f( a, 5 ) );
f = ( A o, int i ) => o.Mul( i );
Console.WriteLine( "Mul: {0}", f( a, 5 ) );

Upvotes: 1

Ray
Ray

Reputation: 46585

You might need to add more details. Delegates are a good option option, as is reflection if you only have the method name, not an actual pointer to it.

Upvotes: 0

Related Questions