Attention: We are retiring the ASP.NET Community Blogs. Learn more >

1 Comment

  • 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);

    }



Comments have been disabled for this content.