Documente Academic
Documente Profesional
Documente Cultură
Chapter 8:
Objectives
This chapter provides complete knowledge on Delegates and Events in C#. At the end
of this chapter participant would be in a position to accomplish the following activities.
Page 1
A delegate object is a special type of object that contains the details of a method rather
than data. Delegates in C# are used for two purposes:
Callback
Event handling
The dictionary meaning of a delegate is a person acting for another person. In C#,
it really means method acting for another method. A delegate in C# is a class type object
and is used to invoke a method that has been encapsulated into it at the time of its
creation. Creating and using delegates involve four types. They include:
Delegate declaration
Delegate instantiation
Delegate method definition
Delegate invocation
A delegate declaration defines a class using the class System. Delegate as a base
class. Delegate methods are any functions whose signatures match the delegate signature
exactly. The delegate instance holds the reference to delegate methods. The instance is
used to invoke the methods indirectly.
Page 2
Inside a class
Outside all classes
When the C# compiler processes delegate types, it automatically generates a sealed class
deriving from System.MulticastDelegate.
Delegate Method:
The method whose references are encapsulated into a delegate instance are
known as delegate methods or callable entities. The signature and return type of
delegate method must exactly mach the signature and return type of the delegate.
One feature of delegates, as pointed out earlier, is that they are type-safe to the extent
that they ensure the matching of signatures of the delegate methods.
However, they do not care
Page 3
The delegate
Delegate void Delegate1();
Can encapsulate references to the following method:
Public void F1()
//instance method
{
Console. WriteLine(F1);
}
Static public void F2()
//static method
{
Console.WriteLine(F2);
}
Delegate Instantiation:
Although delegates are of class type and behave like classes, C# provides a
special syntax for instantiating their instances. A delegate-creation-expression is used to
create a new instance of a delegate.
New delegate-type(expression)
The delegate-type is the name of the delegate declares earlier whose object is to be
created. The expression must be a method name or a value of a delegate-type. If it is a
method name its signature and return type must be the same as those of the delegate.
Consider the following code:
//delegate declaration
Delegate int ProductDelegate (int x, int y);
Class Delegate
{
Static int Product (int a, int b)
{
return (a*b);
}
//delegate instantiation
ProductDelegate p= new productDelegate (Product);
}
Page 4
Delegate Invocation:
C# uses a special syntax for invoking a delegate. When a delegate is invoked, it in
turn invokes the method whose reference has been encapsulated into the delegate,(only if
their signatures match).Invocation takes the following form:
Delegate_object (parameters list)
The optional parameters list provides values for the parameters of the method to be
used.
Example:
delegate int ArithOp(int x, int y);
class MathOperation
{
//delegate method definition
public static int Add(int a, int b)
{
return (a + b);
}
public static int Sub(int a, int b)
{
return (a - b);
}
}
class Program
{
static void Main(string[] args)
{
//Delegate instances
ArithOp operation1 = new ArithOp(MathOperation.Add);
ArithOp operation2 = new ArithOp(MathOperation.Sub);
//invoking instances
int result1 = operation1(100, 200);
int result2 = operation2(200, 100);
Console.WriteLine("Result1= " + result1);
Console.WriteLine("Result2= " + result2);
Page 5
Inheritance of delegates
public delegate void deleg1();
class baseclass
{
public deleg1 del;
}
class DerivedClass : baseclass
{
public DerivedClass()
{
del = new deleg1(func1);
del();
//show();
del = new deleg1(func2);
del();
//show();
}
public void func1()
{
Console.WriteLine("derived class method func1()");
}
public void func2()
{
Console.WriteLine("Derived Class method func2()");
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass dvobj = new DerivedClass();
}
}
}
Page 6
Multicast delegate:
We have seen so far that a delegate can invoke only one method (whose reference
has been encapsulated into the delegate). However, it is possible for certain delegates to
hold and invoke multiple methods. Such delegates are called Multicast delegates.
Multicast delegates are also known as combinable delegates.
If D is a delegate and d1, d2, d3, and d4 are instances of D, then the statements
d3=d1+d2
Page 8
Events:
An event in C# is a way for a class to provide notifications to clients of that class when
some interesting thing happens to an object. The most familiar use for events is in
graphical user interfaces; typically, the classes that represent controls in the interface have
events that are notified when the user does something to the control (for example, click a
button).
As a shortcut to having to build custom methods to add or remove methods to a
delegates invocation list, C# provides the event keyword. These delegate member
variables are always declared private, and therefore they are not directly exposed from
the object firing the event. Defining an event is a two-step process.
First, you need to define a delegate that will hold the list of methods to be called
when the event is fired.
Next, you declare an event (using the C# event keyword) in terms of the related
delegate.
Declaring an event To declare an event inside a class, first a delegate type for the event
must be declared, if none is already declared.
public delegate void ChangedEventHandler(object sender, EventArgs e);
EventArgs is the base class for classes containing event data. The delegate type defines
the set of arguments that are passed to the method that handles the event. Multiple events
Page 9
EventHandler and RateChange are delegates and Click and Rate are events.
Since events are based on delegates, we must first declare a delegate and then declare an
instance of the delegate using the keyword event.
Hooking up to an event From outside the class that declared it, an event looks like a
field, but access to that field is very restricted. The only things that can be done are:
This is done with the += and -= operators. To begin receiving event invocations, client
code first creates a delegate of the event type that refers to the method that should be
invoked from the event. Then it composes that delegate onto any other delegates that the
event might be connected to using +=.
// Add "ListChanged" to the Changed event on "List":
List.Changed += new ChangedEventHandler(ListChanged);
When the client code is done receiving event invocations, it removes its delegate from the
event by using operator -=.
// Detach the event and delete the list:
List.Changed -= new ChangedEventHandler(ListChanged);
Example 1
class MyClass
{
public delegate void Eventhandler(string message);
public event Eventhandler logEvent;
public void process()
{
if (logEvent != null)
{
logEvent("Process () begins");
}
}
}
class Program
{
Page 11
Points to Remember
Delegates provide a built-in, language-supported mechanism for defining and
executing callbacks.
.NET delegate type is the preferred manner to define and respond to callbacks
under the .NET platform.
A delegate in C# is a class type object and is used to invoke a method that has
been encapsulated into it at the time of its creation.
Delegate methods are any functions whose signatures match the delegate
signature exactly.
It is possible for certain delegates to hold and invoke multiple methods. Such
delegates are called Multicast delegates.
When the C# compiler processes delegate types, it automatically generates a
sealed class deriving from System.MulticastDelegate, which contains Invoke(),
BeginInvoke() and EndInvoke() methods.
An event in C# is a way for a class to provide notifications to clients of that class
when some interesting thing happens to an object.
Page 13
Exercise:
Write a Program to Encapsulate more than one method into the delegate and
invoke the methods individually based on requirement.
Write a Program to Show an example for returning a delegate from a method.
Write a Program to Pass delegate as a Parameter for a method and construct the
class.
Write a Program by showing the differences between delegates with anonymous
method and delegates with normal methods.
Write the Scenarios where to use delegates and where to use interfaces.
Page 14