0% found this document useful (0 votes)
18 views8 pages

17.delegates and Events

The document provides an overview of delegates and events in programming, particularly in C#. It explains the concepts of single cast and multicast delegates, their declarations, and how they are used in event handling through a publisher-subscriber model. Additionally, it includes a problem scenario related to a boiler system and demonstrates a solution using delegates and events for logging boiler information.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views8 pages

17.delegates and Events

The document provides an overview of delegates and events in programming, particularly in C#. It explains the concepts of single cast and multicast delegates, their declarations, and how they are used in event handling through a publisher-subscriber model. Additionally, it includes a problem scenario related to a boiler system and demonstrates a solution using delegates and events for logging boiler information.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

ILP Content

CONTENTS

DELEGATES & EVENTS .......................................................................................................................1


1.1 Objective .....................................................................................................................................1
1.2 Delegates ....................................................................................................................................1
1.2.1 Use of Single Cast Delegate ............................................................................................. 1
1.2.2 Multicasting of a Delegate ................................................................................................. 2
1.3 Events .........................................................................................................................................3
1.4 Problem Scenario .......................................................................................................................5
1.5 Approach to solve the problem ...................................................................................................5
1.6 Solution .......................................................................................................................................5
1.7 Explanation about the solution ...................................................................................................7

Internal
ILP Content

DELEGATES & EVENTS

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.

C# delegates are similar to pointers to functions, in C or C++. A delegate is a reference


type variable that holds the reference to a method. The reference can be changed at
runtime.

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.

For example, consider a 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.

Syntax for delegate declaration is:

delegate <return type> <delegate-name> <parameter list>

1.2.1 Use of Single Cast Delegate


The following example demonstrates the use of delegate. The delegate printString can be
used to reference methods that take a string as input and return nothing.

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)
{

// delegate object creation


printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}

1.2.2 Multicasting of a Delegate


Delegate objects can be composed using the "+" operator. A composed delegate calls
the two delegates it was composed from. Only delegates of the same type can be
composed. The "-" operator can be used to remove a component delegate from a
composed delegate.

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;

//observation: A delegate which takes two paramter of integer type.


Class programming
{

public class ExmapleClass


{
public void Add(int x, int y)
{
Console.WriteLine("The sum is: " + (x + y));
}
public void Multiply(int x, int y)
{
Console.WriteLine("The product is: " + (x * y));
}
}

public delegate void fnTwoInteger(int x,int y);


public class DelegateExample
{
public static void Main()
{
ExampleClass obj = new ExampleClass();

fnTwoInteger pointer=null;

//observation: adding more than one function called multicast delegate.

pointer = new fnTwoInteger(obj.Add);


pointer += new fnTwoInteger(obj.Multiply);

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.

Using Delegates with Events

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,

public delegate void BoilerLogHandler(string status);

Next, the event itself is declared, using the event keyword:

//Defining event based on the above delegate

public event BoilerLogHandler BoilerEventLog;

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;

public delegate void NumManipulationHandler();

public event NumManipulationHandler ChangeNum;

protected virtual void OnNumChanged()


{

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.4 Problem Scenario


Scenario 1:
write a program which provides a simple application for troubleshooting for a hot water
boiler system. 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.

1.5 Approach to solve the problem


1. First create a Boiler class perform the operation of boiler system
2. Create event publisher class BoilerLogHandler which will perform the log process and an
function to raise an event
3. The event subscriber class is to define the delegate object and to bind the event handle
to the corresponding instance.

1.6 Solution
using System;
using System.IO;

namespace BoilerEventAppl
{

// boiler class
class Boiler
{
private int temp;
private int pressure;
Internal 5
ILP Content

public Boiler(int t, int p)


{
temp = t;
pressure = p;
}

public int getTemp()


{
return temp;
}
public int getPressure()
{
return pressure;
}
}
// event publisher
class DelegateBoilerEvent
{
public delegate void BoilerLogHandler(string status);

//Defining event based on the above delegate


public event BoilerLogHandler BoilerEventLog;

public void LogProcess()


{
string remarks = "O. K";
Boiler b = new Boiler(100, 12);
int t = b.getTemp();
int p = b.getPressure();
if(t > 150 || t < 80 || p < 12 || p > 15)
{
remarks = "Need Maintenance";
}
OnBoilerEventLog("Logging Info:\n");
OnBoilerEventLog("Temparature " + t + "\nPressure: " + p);
OnBoilerEventLog("\nMessage: " + remarks);
}

protected void OnBoilerEventLog(string message)


{
if (BoilerEventLog != null)
{
BoilerEventLog(message);
}
}
}
// this class keeps a provision for writing into the log file
class BoilerInfoLogger
{
FileStream fs;
StreamWriter sw;
public BoilerInfoLogger(string filename)
{
fs = new FileStream(filename, FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
}
Internal 6
ILP Content

public void Logger(string info)


{
sw.WriteLine(info);
}
public void Close()
{
sw.Close();
fs.Close();
}
}
// The event subscriber
public class RecordBoilerInfo
{
static void Logger(string info)
{
Console.WriteLine(info);
}//end of Logger

static void Main(string[] args)


{
BoilerInfoLogger filelog = new BoilerInfoLogger("e:\\boiler.txt");
DelegateBoilerEvent boilerEvent = new DelegateBoilerEvent();
boilerEvent.BoilerEventLog += new
DelegateBoilerEvent.BoilerLogHandler(Logger);
boilerEvent.BoilerEventLog += new
DelegateBoilerEvent.BoilerLogHandler(filelog.Logger);
boilerEvent.LogProcess();
Console.ReadLine();
filelog.Close();
}//end of main

}//end of RecordBoilerInfo
}

1.7 Explanation about the solution

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

You might also like