0

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?

0

2 Answers 2

6

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(); } 
Sign up to request clarification or add additional context in comments.

2 Comments

How would I use the pass an action? Say I wanted to show a Hello World message box.
@Michael: Something like this: PassAnAction(() => ShowMessageBox("Hello world")). (I don't know what you're using for showing message boxes, but hopefully that gives you an idea.)
1
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), ...) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.