Delegates
A delegate is an object that can refer to a method.
When you create a delegate, you are creating an object that can hold a
reference to a method. Thus, the method can be called through this reference.
A delegate in C# is similar to a function pointer in C/C++.
The same delegate can be used to call different methods during the
runtime of a program by simply changing the method to which the delegate
refers.
The method that will be invoked by a delegate is not determined at compile
time, but rather at runtime. This is the principal advantage of a delegate.
A delegate is declared using the keyword delegate. The general form of
a delegate declaration is shown here: delegate ret-type name(parameter-list);
·
ret-type is
the type of value returned by the methods that the delegate will be calling
·
The name of
the delegate is specified by name.
·
The
parameters required by the methods called through the delegate are specified in
the parameter-list.
A delegate can call only methods whose return type and parameter list
match those specified by the delegate’s declaration.
The principal advantage of an array is that it organizes data in such
a way that it can be easily manipulated.
Also, arrays organize data in
such a way that it can be easily sorted.
Arrays in C# can also be implemented as objects. By implementing
arrays as objects, several important advantages are gained, and the unused
arrays will be garbage-collected.
Delegate Method Group Conversion
C# 2.0 added an option that significantly simplifies the syntax that
assigns a method to a delegate. This feature is called method group conversion,
It allows assigning the name of a method to a delegate, without the
use of new or explicitly invoking the delegate’s constructor.
Multicasting
Multicasting is the ability to create an invocation list, or chain, of
methods that will be automatically called when a delegate is invoked.
To add methods to the chain, Instantiate a delegate, and then use the
+ or += operator
To remove a method, use − or − =.
Events
An event is, essentially, an automatic notification that some action
has occurred.
An object that has an interest in an event registers an event handler
for that event. When the event occurs, all registered handlers are called.
Event handlers are represented by delegates
Events are members of a class and are declared using the event keyword. event event-delegate object-name;
·
event-delegate
is the name of the delegate used to support the event.
·
object-name
is the name of the specific event object being created.
Multicast Event
Like delegates, events can be multicast. This enables multiple objects
to respond to an event notification. |