Michael
Michael

Reputation: 157

Having a function as an argument

I am trying to make a new Timers class to aid with my learning of c#. How would I let an argument for a function be a function?

Upvotes: 0

Views: 91

Answers (2)

Dmitry
Dmitry

Reputation: 17350

public class MyTimer {
    private readonly Action _fireOnInterval;

    public MyTimer(Action fireOnInterval, TimeSpan interval, ...) {
        if (fireOnInterval == null) {
            throw new ArgumentNullException("fireOnInterval");
        }
        _fireOnInterval = fireOnInterval;
    }

    private void Fire() {
        _fireOnInterval();
    }
    ...
}

You can call it like this:

new MyTimer(() => MessageBox.Show("Elapsed"), TimeSpan.FromMinutes(5), ...)

Upvotes: 1

StriplingWarrior
StriplingWarrior

Reputation: 156524

It's pretty simple. Just make the argument be some kind of delegate type, like Action or Func.

void PassAnAction(Action action)
{
    action(); // call the action
}

T PassAFunction<T>(Func<T> function)
{
    return function();
}

Upvotes: 6

Related Questions