Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break loop inside a delegate

I created simple class, which can use to create loops:

public class SimpleLoop
{
    public int I { get; set; }
    public Predicate<int> Condition { get; set; }
    public int Increment { get; set; }
    public Action<int> Action { get; set; }

    public SimpleLoop(int i, Predicate<int> condition, int increment, Action<int> action)
    {
        I = i;
        Condition = condition;
        Increment = increment;
        Action = action;
        Invoke();
    }

    private void Invoke()
    {
        for (int i = I; Condition.Invoke(i); i += Increment)
        {
            Action.Invoke(i);
        }
    }
}

Then I can call this loop this way:

new SimpleLoop(0, i => i <= 12, 1, delegate (int i)
{
    Console.WriteLine(i);
});

Everything works fine, but I don't know how to break out of the loop, because I can't use the keywords break and continue inside a void. I found out that I can use return to get same effect as continue, but I can't break out of the loop.

I also created other "loop classes" on the base of this class. They look quite similar, but there I use a customized delegate instead of Action

like image 788
daniel59 Avatar asked Dec 17 '25 16:12

daniel59


1 Answers

Why not just use a Func<int, bool> instead of Action<int>, and require that the delegate return true to continue or false to break?

For example:

public class SimpleLoop
{
    public int I { get; set; }
    public Predicate<int> Condition { get; set; }
    public int Increment { get; set; }
    public Func<int, bool> Action { get; set; }

    public SimpleLoop(int i, Predicate<int> condition, int increment, Func<int, bool> action)
    {
        I = i;
        Condition = condition;
        Increment = increment;
        Action = action;
        Invoke();
    }

    private void Invoke()
    {
        for (int i = I; Condition.Invoke(i); i += Increment)
        {
            if (!Action.Invoke(i))
                break;
        }
    }
}

And then:

new SimpleLoop(0, i => i <= 12, 1, delegate (int i)
{
    Console.WriteLine(i);
    return i < 5;
});
like image 110
Matthew Watson Avatar answered Dec 19 '25 05:12

Matthew Watson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!