Delegates are complicated fellows, and you can do a lot with them - but in many cases developers don;t even realise they are involved at all ...
Events are all delegate based; a delegate is a collection of function pointers which provide the mechanism for you to add handlers:
DynamicArgument da = DynamicArgument.Create();
da.ArgumentReceived += Application_ArgumentReceived;
private void Application_ArgumentReceived(object sender, DynamicArgument.DynamicArgmentEventArgs e)
{
tbData.Text += "\r\n" + e.Argument;
}
ArgumentReceived
is a delegate, which adds your handler to the event chain so that when the
DynamicArgument
class raises the event, all the methods that has "subscribed" to the delegate will get executed in turn. But you don't really see that until you start creating your own Events for a class - and even then in modern code, the delegate itself is "hidden" behind a layor of abstraction:
public event EventHandler<DynamicArgmentEventArgs> ArgumentReceived;
protected virtual void OnArgumentReceived(DynamicArgmentEventArgs e)
{
ArgumentReceived?.Invoke(this, e);
}
But that's not the only thing you can do with them: you can use an array of delegates to select a function to execute: which is pretty much what a
switch
block does: it =uses an index into an array of delegates to run a specific piece of code instead of having to do
if ... else if ... else if ... else
.
You can use them to pass a specific print method into a generic system: perhaps you want the same code to generate different results for a supervisor and a peon? Use a delegate as a parameter and you can pass the right method and the remaining code is unchanged.
Loads of things you can do with them - most of which you will meet when you get a little further in your course!