Hi Stephen,
Stephen said:
I am new to C# and can't get my head round what delegates
are and what they are for. can anyone enlighten me?
Delegates are glorified function pointers (if that means anything to
you). Delegates support two related concepts.
1. Plugging in functionality into classes that are already built.
2. Call-backs.
An example of #1 is the Thread class. How do you tell a thread what you
want it to do? In a world without delegates, the Thread class could have
designed to accept a reference to an interface that defines a single method.
The Thread object would call the single method of the interface when the
thread was started. Of course, to create a class which implements the single
method and then create an instance of that class to pass to the Thread
instance seems a bit much. With delegates you can just say "Hey Thread
object, call *this* function".
An example of #2 is asynchronous methods. You don't want to freeze your
app while you're waiting around for the web service method you just called
to get back to you. No problem, you can call the web service method
asynchronously (i.e. control returns to your app before the web service
method completes). But how do you know when the web service method is done?
Polling isn't very efficient (Are you done, yet?...Are you done, yet?...Are
you...). Call-backs are the answer. You just give the asynchronous method a
method (in your app, presumably) to call when it's done.
Delegates also support events, which are somewhat more managed versions
of delegates. For example, events prevent one object from inadvertently (or
"vertantly") wiping out the event sinks of another. Delegates are a relative
free-for-all.
I hope that was somewhat lucid.
Regards,
Dan