Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delegate to private function as argument for method in different class

Let's take class A with private methods f() and g(). Let class B have public method h. Is it possible to pass pointer/delegate pointing to A.g from method A.f to B.h?

Consider the following code:

Class B
{
    public B() {}

    public h(/*take pointer/delegate*/)
    {
        //execute method from argument
    }
}

Class A
{
    private int x = 0;
    private void g()
    {
        x = 5;
    }

    private void f()
    {
        B b = new B();
        b.h(/*somehow pass delegate to g here*/);
    }
}

After A.f() is called I would like A.x to be 5. Is it possible? If so, how?

like image 717
Mr M. Avatar asked May 20 '15 22:05

Mr M.


2 Answers

You could create an Action argument to your method:

public h(Action action)
{
    action();
}

and then call it like this:

b.h(this.g);

Possibly worth noting that there are generic versions of Action that represent methods with parameters. For example, an Action<int> would match any method with a single int parameter.

like image 53
Dan Puzey Avatar answered Oct 20 '22 05:10

Dan Puzey


Yes it is.

class B
{
    public B()
    {
    }

    public void h(Action func)
    {
        func.Invoke();
        // or
        func();
    }
}

class A
{
    private int x = 0;

    private void g()
    {
        x = 5;
    }

    private void f()
    {
        B b = new B();
        b.h(g);
    }
}
like image 32
Gigo Avatar answered Oct 20 '22 03:10

Gigo