Search code examples
c#delegatesactionpredicate

C# send actions from 1 scope to another


I couldn't find what I'm looking for, I tried different ways and none seems to work.

There is any way for this to work?

public class A
{
    public void B(int num)
    {
        for (int i = 0; i < num; i++)
            Console.WriteLine("Executing B..");
    }
    public void C(Action action)
    {
        action();
        Console.WriteLine("Executing C..");
        action();
    }
}
    
public static void Main(string[] args)
{
    int z = 2;
    var a = new A();
    a.C(likePredicate => {
        likePredicate.B(z);
    });
}

The idea is to get the next result..

Executing B..
Executing B..
Executing C..
Executing B..
Executing B..

Thank you.


Solution

  • I finally did it, this is the code to maintain the specific object in the lambda

    public class A
    {
        public void B(int num)
        {
            for (int i = 0; i < num; i++)
                Console.WriteLine("Executing B..");
        }
        public void C(Action<A> action)
        {
            action?.Invoke(this);
            Console.WriteLine("Executing C..");
            action?.Invoke(this);
        }
    }
    
    public static void Main(string[] args)
    {
        int z = 2;
        var a = new A();
        a.C(e => {
            e.B(z);
        });
    }
    

    Thanks to @NotTheDr01ds to teach me how to properly answer my own question in other post and not editing my own.