Given that \'most\' developers are Business application developers, the features of our favorite programming languages are used in the context of what we
Delegates are often used for event dispatch, however that's only because they are convenient to do so. Delegates are useful for any kind of method invocation. They also have a number of additional features, such as the ability to invoke asynchronously.
The basic reason for a delegate though is to provide a Closure, or the ability to call a function along with it's state, which is usually an object instance.
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().