Joe Sonderegger
Joe Sonderegger

Reputation: 804

Calling a delegate on two functions

Consider the following class:

class A
{
void f1(int a){}
void f2(int b){}
}

I would like to do the following:

A a = new A();
A b = new B();

Func f = A.f1(1); //A function that has already got arguments.
Func ff = A.f1(10); //A function that has already got arguments.

a.f(); //Calls a.f1(1);
a.ff(); //Calls a.f1(10);
b.f(); //Calls b.f1(1);

I don't think it works but I am happy if someone can prove me wrong.

Upvotes: 1

Views: 207

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

You should use closures to capture function arguments:

Action f = () => a.f1(1);
Action ff = () => a.f1(10);

And later you can call:

f();  // calls a.f1(1)
ff(); // calls a.f1(10)

If you want to call f1 method on a or b instances (I assume you have B : A inheritance here), then you should use Action<T> delegate which will accept instance to call f1 method on:

Action<A> f = x => x.f1(42);

And invoke this action with instace on which you want to run method f1 with captured argument falue (42):

f(a); // calls a.f1(42)
f(b); // calls b.f1(42)

Upvotes: 6

Related Questions