Ginny said:
Hi, Thanks for your reply.
1. Well, this could have simply be done by calling the method directly.
Why
are we going round robin and calling the method through the delegate.
Imagine in the case of the example given that the check for which delegate
to use is done once and the results stored somewhere else, to be used
multiple time later. That would be more similar to the usual use of a
delegate.
You are right that if the check is immediately followed by the use, one
could just call the methods directly. But the situations in which a
delegate is actually used aren't actually so simple. I suspect that the
example Vadym gave was just oversimplified in an attempt at clarity. It
doesn't mean that delegates aren't useful.
One of the most common ways a delegate is used in .NET is for event
handling. Even at compile time, a .NET class may not know what method will
be called in response to an event being handled, and/or more than one method
might need to be called. Using delegates allows the code to resolve the
called method at runtime, as well as allows the code to maintain a list of
methods to be called at runtime.
There are lots of situations in which delegates are useful, and for the most
part they are similar to the reasons that one would use a function pointer
in C.
2. Delegates does help in some manner at least but not the way it has been
exaggerated. It simply is a pointer at the end of the day.
What do you mean by "the way it has been exaggerated"? I haven't seen any
documentation that exaggerates the use of delegates.
Also, a delegate is not "a pointer at the end of the day". I'd agree that
the distinction is small, but there are no pointers in safe .NET code. As
with practically everything else, a delegate is an object that can be
referenced via the usual .NET syntax. It is more than just a pointer.
One key difference is that the type of the delegate is attached to the
delegate. In C, if you get a function pointer, the type for that pointer is
determined at compile time by the type of whatever variables in which it is
stored. If you cast a C function pointer to a void* and then back to a
function pointer, there is no way at run time to ensure that the new
function pointer type matches the actual function in question. In .NET, all
of this information is persistent and the CLR can do the necessary checks
even at runtime to ensure correct use of a delegate.
As with everything else in .NET, a delegate is "type safe".
It's true that delegates are used in .NET in very much the same way that
function pointers are used in C. But they aren't exactly the same.
Pete