Given that \'most\' developers are Business application developers, the features of our favorite programming languages are used in the context of what we
Another great use of delegates is as state machines. If your program logic contains repeated if...then statements to control what state it is in, or if you're using complicated switch blocks, you can easily use them to replicate the State pattern.
enum State {
Loading,
Processing,
Waiting,
Invalid
}
delegate void StateFunc();
public class StateMachine {
StateFunc[] funcs; // These would be initialized through a constructor or mutator
State curState;
public void SwitchState(State state) {
curState = state;
}
public void RunState() {
funcs[curState]();
}
}
My 2.0 delegate syntax may be rusty, but that's a pretty simple example of a state dispatcher. Also remember that delegates in C# can execute more than one function, allowing you to have a state machine that executes arbitrarily many functions each RunState().