Events and Delegates - C# Programming for Beginners (2015)

C# Programming for Beginners (2015)

Chapter 9: Events and Delegates

In this chapter, we are going to study two very important concepts in C#: Delegates and Events. C#’s entire event handling mechanism is based on these two concepts. Delegates in C# are function pointers. They hold reference to a function. They provide decoupling between the calling function and the function being called. An event in C# is also a type of delegate. Events are used to invoke methods. For instance, when you click a button, an event fires which invokes all the methods associated with the event. In this chapter, we shall see these concepts in action.

Contents

· Delegates

· Events

1- Delegates

Delegates are classes which invoke a method which is passed to its constructor. Delegates store references to the method which is passed to it as a delegate. The first example of this chapter demonstrates how a delegate is created and how it is used to reference a method.

Example1:

using System;

namespaceMyCSharpApplication

{

public delegate intChangeIt(intnum);

class Program

{

static void Main(string[] args)

{

ChangeIt c = square;

Console.WriteLine("The square of 4 is: "+ c(4));

Console.Read();

}

public static int square(intnum)

{

returnnum * num;

}

}

}

In Example1, we created a delegate, “ChangeIt”, by using the keyword “delegate”. A delegate can only store references to methods that exactly match the signature of the delegate. For instance, in Example 1, the delegate signature is “intChangeit (intnum)”. This means that this delegate can call any method which accepts an integer type variable as a parameter and returns an integer type variable. In the “Program” class, we created a static method called “square”. The signature of this method matches the signature of the “ChangeIt” delegate. Inside the “Main” method, we create a variable, “c”, of the delegate “ChangeIt” and assign it the method “square”. To invoke the method, we simply pass the parameter to variable “c”. For instance, if we pass 4 to variable “c”, the value returned would be 16 because, internally, “c” would call the “square” method. We then display the returned value on the screen.

Output1:

The square of 4 is: 16

2- Events

Events are also a type of delegate; however, during declaration, the keyword “event” is appended before the delegate name. Like delegates, events are also hooked to methods. Events can execute methods with a signature similar to the signature of the delegate type of the event. When the event is fired, one or more methods can be executed. Example2 demonstrates how events are hooked to methods and how these methods are called when an event is fired.

Example2:

using System;

namespaceMyCSharpApplication

{

public delegate void DisplayNameHandler();

class Program

{

public static event DisplayNameHandlerNameChanged;

static void Main(string[] args)

{

NameChanged += DisplayFruit;

NameChanged += DisplayAnimal;

NameChanged += DisplayFlower;

NameChanged += DisplayColor;

NameChanged.Invoke();

Console.Read();

}

public static void DisplayFruit()

{

Console.WriteLine("This is an apple.");

}

public static void DisplayAnimal()

{

Console.WriteLine("This is a lion.");

}

public static void DisplayFlower()

{

Console.WriteLine("This is a rose.");

}

public static void DisplayColor()

{

Console.WriteLine("This is red.");

}

}

}

In Example 2, we created a delegate named “DisplayNameHandler”. Inside the “Program” class, we created an event “NameChanged” of the delegate type “DisplayNameHandler”. We declared four methods: “DisplayFruit”, “DisplayAnimal”, “DisplayFlower”, and “DisplayColor”. The signature of these methods is similar to the “DisplayNameHandler”; therefore, we can hook these four methods to the “NameChanged” event. To hook a method with any event, we simply add that method to the event name. In Example 1, the statement “NameChanged += DisplayFruit” depicts the hooking of method “DisplayFruit” to the "NameChanged” event. To fire an event, we simply call the “Invoke” method on that event. “Invoke” executes all the methods hooked with the “NameChanged” event in the order in which they are hooked. The output of the code in Example2 is as follows.

Output2:

This is an apple.

This is a lion.

This is a rose.

This is red.

Exercise 9

Task:

Create a delegate named “Calculations” which accepts two integer type parameters and returns one integer type value. In the “Program” class, create two methods, “sum” and “subtract”, which have the same signature as the “Calculations” delegate. Create an object of the “Calculation” delegate and hook both the “sum” and “subtract” methods to it. Perform “sum” and “subtraction” on two random integers using the object of “Calculation” delegate hooked to the “sum” and “subtract” methods.

Solution

using System;

namespaceMyCSharpApplication

{

public delegate int Calculations(int num1, int num2);

class Program

{

static void Main(string[] args)

{

Calculations c = Sum;

c(10, 5);

Console.WriteLine(c(10, 5));

c += Subtract;

Console.WriteLine(c(10, 5));

Console.Read();

}

public static int Sum(int num1, int num2)

{

return num1 + num2;

}

public static int Subtract (int num1, int num2)

{

return num1 - num2;

}

}

}