Optional parameter in lambda

Viewed 27

Can I reduce the number of methods needed in my class to accomplish running code in a lambda, with optional parameters?

I created a class where I can run code repeatedly like this:

Scheduler.InvokeRepeated(1.0f, () => { ... // Do things forever });

I also want to be able to easily cancel a running code like this:

Scheduler.InvokeRepeated(1.0f, (runningAction) => {
    ... // Do things for a while
    if (exit) {
        runningAction.Cancel();
    }
});

But I don't want to force the user to specify that runningAction parameter. So this is my class:

    public static RunningAction InvokeRepeated(float interval, Action action)
    {
        // Call InvokeAt with an "action" parameter.
        return InvokeAt(currentTime + interval, interval, action, null);
    }

    public static RunningAction InvokeRepeated(float interval, Action<RunningAction> actionWithParam)
    {
        // Call InvokeAt with an "actionWithParam" parameter.
        return InvokeAt(currentTime + interval, interval, null, actionWithParam);
    }

    private static RunningAction InvokeAt(float time, float interval, Action<> action, Action<RunningAction> actionWithParam)
    {
        ... // Do things depending on whether action is null or actionWithParam is null
    }

Now imagine that I have a lot of methods for specifying a first delay, and then an interval. Or just something that runs delayed once, or twice, and doesn't repeat etc.

So that means I have to duplicate every method to include these two different kinds of 'Action's. But if possible I'd rather just have one method.

I tried creating my own delegate, instead of using Action:

    public delegate void MyDelegate(RunningAction arg = null);

But that didn't allow me to call it without specifying a parameter.

Could you also point me to where I can read up on stuff like this? Weird things you can and can't do with generics and delegates?

0 Answers
Related