Delegates and Events
Delegates and Events are two very powerful features of .NET.
Events: cornerstone of GUI programming
Delegates:
• implement events.
• class
that encapsulates a method signature.
• equivalent
to function pointers.
• "unlike
function pointers, delegates are object oriented and type-safe.”
• serves
as the basis for the event-handling model in C# but can be used in a context
removed from event handling.
• allows
to pass references of entry points to methods and invoke them without making an
explicit method call.
• defines
the signature of the method it can call.
Events and delegates- Difference
Events are the actions of the system on user manipulations
(e.g. mouse clicks, key press, timer etc.) or any event triggered by the
program.
Delegate is type which holds the method(s) reference in an object.
Delegate is type which holds the method(s) reference in an object.
Event is a C# Modifier.
Delegate is a C# type.
Delegate is a C# type.
Types of delegates
Delegate is a class and is inherited from base delegate
class of .NET class library when it is declared which can be from either System.Delegate
or System.MulticastDelegate.
Two types of delegates: Singlecast and Multiplecast
delegates
1. Singlecast delegate:
• point
to single method at a time.
• delegate
is assigned to a single method at a time.
• derived
from System.Delegate class.
2. Multicast Delegate:
• a
delegate is wrapped with more than one method.
• In
C#, delegates are multicast; they can point to more than one function at a
time.
• derived
from System.MulticastDelegate class.
Defining and using delegates
There are three steps in defining and using delegates:
- Declaration
- Instantiation
- Invocation
1. Declaration
• keyword
‘delegate ’
[attributes]
[modifiers] delegate ReturnType Name ([formal-parameters]);
• attributes
factor : normal C# attribute.
• modifier
: new, public, private, protected, or internal.
• ReturnType:
data types; can also be a type void or name of class.
• Name:
valid C# name.
• Parentheses
is required . If this method will not take any argument, leave the parentheses
empty.
Example:
public delegate void DelegateExample();
//delegate with return type
//void and accept no
//parameters.
2. Instantiation
DelegateExample d1
= new DelegateExample(Display);
3. Invocation
d1();
Working of delegates
Documentation details about how delegates work:
- A
delegate declaration defines a class that is derived from the class System.Delegate.
- A delegate
instance encapsulates an invocation list, which is a list of one or more
methods, each of which is referred to as a callable entity.
- For
instance methods, a callable entity consists of an instance and a method
on that instance.
- For
static methods, a callable entity consists of just a method.
- Invoking
a delegate instance with an appropriate set of arguments causes each of
the delegate instance's callable entities to be invoked with the given set
of arguments.
Benefits of delegates
- Delegates
are object oriented and type-safe and secure as they ensure that the
signature of the method being called is correct.
- Delegate
helps in code optimization.
Usage areas of delegates
- The
most common example of using delegates is in events.
- They
are extensively used in threading
- Delegates
are also used for generic class libraries, which have generic
functionality, defined.
An Anonymous Delegate
• No
need to explicitly define a method prior to using the delegate.
• if
a delegate itself contains its method definition it is known as anonymous
method.
• Sample
program and output is shown below:
Point to remember about Delegates:
- are
similar to C++ function pointers, but are type safe.
- gives
a name to a method signature.
- allow
methods to be passed as parameters.
- can
be used to define callback methods.
- can
be chained together; for e.g. multiple methods can be called on a single
event.
- C#
version 2.0 introduces the concept of Anonymous Methods, which permit code
blocks to be passed as parameters in place of a separately defined method.
- helps
in code optimization.
Events
• event:
message sent by an object to signal occurrence of an action.
• Action:
user interaction/ triggered by some other program logic.
• Event
sender: The object that raises the event.
• Event
receiver: The object that captures the event and responds.
Prerequisites for raising an event:
- A
class that provides event data.
- An
event delegate.
- The
class that raises the event.
By convention in the .NET Framework, when an event is raised,
it passes event data to its event handlers. The event data is provided by the System.EventArgs
class or by a class that is derived from it.
Declaring Events
• directly
tied to a delegate.
• A
delegate object encapsulates a method so that it can be called anonymously.
• An
event is a mechanism by which a client class can pass delegates to methods that
need to be invoked whenever something happens.
• When
it does, the delegate(s) given to it by its clients are invoked.
Syntax to declare an event in C# :
public
delegate void testDelegate(int a);
public event
testDelegate MyEvent;
• Once
an event is declared, it must be associated with one or more event handlers
before it can be raised.
• An event handler is a method that is called
using a delegate.
• += operator is used to
associate an event with an instance of a delegate that already exists.
For example:
Myform.MyEvent +=
new testEvent(MyMethod);
An event handler may also be detached as follows:
MyForm.MyEvent -=
new testEvent(MyMethod);
How does the event keyword work ?
Whenever an event is defined for a class, the compiler
generates three methods that are used to manage the underlying delegate i.e.:
- add_<EventName>:
• public
method that calls the static Combine method of System.Delegate to
add another method to its internal invocation list.
• This
method is however not used explicitly.
• The
same effect is achieved by using the += operator as specified before.
2. remove_<EventName>:
• public method that calls the
static Remove method of System.Delegate to
remove a
receiver from the event’s invocation list.
• This method is also not called directly.
• -= operator.
3. raise_<EventName>:
• A protected method that calls the
compiler generated Invoke method of the delegate, to call each method
in the invocation list.
Delegates and Events in Windows Forms
• Default
delegates are provided for the events of the controls and classes of the .NET
Framework base class library.
• When
using Windows Forms to create rich client applications, events can be handled
in two ways:
- By
declaring a method that has a signature that is the same as the
corresponding event handler delegate and then registering the method as a
handler (using +=).
- By
overriding the corresponding event method, when your class is a subclass
of the Control class.
0 comments:
Post a Comment