17.delegates and Events
17.delegates and Events
CONTENTS
Internal
ILP Content
1.1 Objective
This is to enable understanding the basic concepts of Delegates and Events
1.2 Delegates
In programming, you are often faced with situations where you need to execute a
particular action, but you don't know in advance which method, or even which object,
you'll want to call upon to execute it. For example, you might want to tell an object to play
a media file during runtime, but you might not know what object will be playing the file, or
whether it's a video, a sound file, an animation, or something else. Rather than
hardcoding a particular media player object, you would create a delegate, and then
resolve that delegate to a particular method when the program executes.
Delegates are especially used for implementing events and the call-back methods. All
delegates are implicitly derived from the System.Delegate class.
Declaring Delegates
Delegate declaration determines the methods that can be referenced by the delegate. A
delegate can refer to a method, which have the same signature as that of the delegate.
public delegate int MyDelegate (string s);The preceding delegate can be used to
reference any method that has a single string parameter and returns an int type variable.
We use this delegate to call two methods, the first prints the string to the console, and the
second one prints it to a file:
Internal 1
ILP Content
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// delegate declaration
public delegate void printString(string s);
// this method prints to the console
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
//this method prints to a file
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt",
FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush();
sw.Close();
fs.Close();
}
// this method takes the delegate as parameter and uses it to
// call the methods as required
public static void sendString(printString ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
Using this useful property of delegates you can create an invocation list of methods that
Internal 2
ILP Content
will be called when a delegate is invoked. This is called multi-casting of a delegate. The
following program demonstrates multi-casting of a delegate:
using System;
fnTwoInteger pointer=null;
pointer(52, 72);
Console.ReadLine();
}
}
}
1.3 Events
Events are basically a user action like key press, clicks, mouse movements, etc., or some
occurrence like system generated notifications. Applications need to respond to events when they
occur. For example, interrupts. Events are used for inter-process communication.
The events are declared and raised in a class and associated with the event handlers
using delegates within the same class or some other class. The class containing the event is
Internal 3
ILP Content
used to publish the event. This is called the publisher class. Some other class that accepts this
event is called the subscriber class. Events use the publisher-subscriber model.
A publisher is an object that contains the definition of the event and the delegate. The
event-delegate association is also defined in this object. A publisher class object invokes the
event and it is notified to other objects.
A subscriber is an object that accepts the event and provides an event handler. The
delegate in the publisher class invokes the method (event handler) of the subscriber class.
Declaring Events
To declare an event inside a class, first a delegate type for the event must be declared.
For example,
The preceding code defines a delegate named BoilerLogHandler and an event named
BoilerEventLog, which invokes the delegate when it is raised.
using System;
namespace SimpleEvent
{
using System;
public class MainClass
{
public static void Main()
{
EventTest e = new EventTest(5);
e.SetValue(7);
e.SetValue(11);
Console.ReadKey();
}
}
public class EventTest
{
private int value;
if (ChangeNum != null)
{
ChangeNum();
}
else
Internal 4
ILP Content
{
Console.WriteLine("Event fired!");
}
}
public EventTest(int n )
{
SetValue(n);
}
public void SetValue(int n)
{
if (value != n)
{
value = n;
OnNumChanged();
}
}
}
1.6 Solution
using System;
using System.IO;
namespace BoilerEventAppl
{
// boiler class
class Boiler
{
private int temp;
private int pressure;
Internal 5
ILP Content
}//end of RecordBoilerInfo
}
When the maintenance engineer inspects the boiler, the boiler temperature and pressure is automatically
recorded into a log file along with the remarks of the maintenance engineer.
Logging info:
Temperature 100
Pressure 12
Message: O. K
Internal 7