Passing Methods As Parameters: Delegates to the Answer

Question:
Is it possible to pass a method (or method address) to another method so that, if conditions warrent, that passed method can be called?

Answer:
http://scottwater.com/blog/articles/DelegatingMethods.aspx

Published Wednesday, March 31, 2004 10:14 AM by StarPilot
Filed under:

Comments

# re: Passing Methods As Parameters: Delegates to the Answer

Wednesday, March 31, 2004 4:25 PM by Raymond Chen
This is almost but not quite the same as passing a method as a parameter. A delegate is a method *and an instance* (or a static method with no instance).

Consider

class C {
public void Do(int x) { ... }
public void Die(int x) { ... }
}

and I want to pass the method "Do" like this:

void Action(C[] ary, magicphrase action)
{
foreach (C c in ary) c.action(3);
}

A delegate doesn't quite work here because you would bind each object "c" to the action, so that this Action function receives not an array of C[] but rather an array of delegates.

Action(
new ActionDelegate[] {
new ActionDelegate(ary[0].Do),
new ActionDelegate(ary[1].Do),
new ActionDelegate(ary[2].Do),
new ActionDelegate(ary[3].Do) });

To be able to pass just the method you need a thunk.

class C {
static void DoIndirect(C c, int x) {
c.Do(x);
}
}

Now you can call Action

Action(ary, new IndirectAction(C.DoIndirect));

where Action is

void Action(C[] ary, IndirectAction action)
{
foreach (C c in ary) action(c, 3);
}

Leave a Comment

(required) 
(required) 
(optional)
(required)