0% found this document useful (0 votes)
31 views15 pages

Ex 6

The document provides an in-depth overview of delegates and events in C# .NET, explaining their purpose, characteristics, and how to define and use them effectively. It covers topics such as delegate instantiation, anonymous methods, multicast delegates, and handling exceptions in delegate invocation. The article aims to enhance understanding of how delegates function as type-safe method references and facilitate callback mechanisms in programming.

Uploaded by

gangursahil
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)
31 views15 pages

Ex 6

The document provides an in-depth overview of delegates and events in C# .NET, explaining their purpose, characteristics, and how to define and use them effectively. It covers topics such as delegate instantiation, anonymous methods, multicast delegates, and handling exceptions in delegate invocation. The article aims to enhance understanding of how delegates function as type-safe method references and facilitate callback mechanisms in programming.

Uploaded by

gangursahil
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/ 15

5/10/24, 4:25 PM Mastering Delegates and Events In C# .

NET

Mastering Delegates and Events In C# .NET


Vidya Vrat Agarwal Feb 12, 2023 865.9k 47 35

Introduction
Delegates in C# provide a way to define and execute callbacks. Their flexibility allows you to
define the exact signature of the callback, and that information becomes part of the delegate
type itself. Delegates are type-safe, object-oriented, and secure. In this article, you will learn
how to create and manipulate delegate types and C# events that streamline the process of
working with delegate types.

Delegates in C#
A Delegate is an abstraction of one or more function pointers (as existed in C++; the
explanation about this is out of the scope of this article). The .NET has implemented the
concept of function pointers in the form of delegates. With delegates, you can treat a function
as data. Delegates allow functions to be passed as parameters, returned from a function as a
value, and stored in an array. Delegates have the following characteristics:

Delegates are derived from the System.MulticastDelegate class.


They have a signature and a return type. A function that is added to delegates must be
compatible with this signature.
Delegates can point to either static or instance methods.
Once a delegate object has been created, it may invoke the methods it points to at
runtime.
Delegates can call methods synchronously and asynchronously.

A delegate contains a couple of useful fields. The first is a reference to an object, and the
second is a method pointer. When invoking the delegate, the instance method is called on the
contained reference. However, if the object reference is null, then the runtime understands this
to mean that the method is static. Moreover, invoking a delegate syntactically is the exact same
as calling a regular function. Therefore, delegates are perfect for implementing callbacks.

Why Do We Need Delegates


Historically, the Windows API frequently used C-style function pointers to create callback
functions. Using a callback, programmers could configure one function to report back to
another function in the application. So the objective of using a callback is to handle button-
clicking, menu-selection, and mouse-moving activities. But the problem with this traditional
approach is that the callback functions were not type-safe. In the .NET framework, callbacks are
still possible using delegates with a more efficient approach. However, delegates maintain three
important pieces of information, as in the following:

The parameters of the method.

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 1/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

The address of the method it calls.


The return type of the method.

A delegate is a solution for situations where you want to pass methods around to other
methods. You are so accustomed to passing data to methods as parameters that the idea of
passing methods as an argument instead of data might sound a little strange. However, there
are cases where you have a method that does something, for instance, invoking another
method. You do not know at compile time what this second method is. That information is
available only at runtime; hence Delegates are the device to overcome such complications.

Define a Delegate in C#
A delegate can be defined as a delegate type. Its definition must be similar to the function
signature. A delegate can be defined in a namespace and within a class. A delegate cannot be
used as a data member of a class or local variable within a method. The prototype for defining
a delegate type is as the following;

accessibility delegate return type delegatename(parameterlist);

Delegate declarations look almost exactly like abstract method declarations, and you replace
the abstract keyword with the delegate keyword. The following is a valid delegate declaration:

1 public delegate int operation(int x, int y);

When the C# compiler encounters this line, it defines a type derived from MulticastDelegate,
which also implements a method named Invoke that has the same signature as the method
described in the delegate declaration. For all practical purposes, that class looks like the
following:

1 public class operation : System.MulticastDelegate


2 {
3 public double Invoke(int x, int y);
4 // Other code
5 }

As you can see using ILDASM.exe, the compiler-generated operation class defines three public
methods as in the following:

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 2/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

Figure 1.1
After you have defined a delegate, you can create an instance of it so that you can use it to
store the details of a particular method.
Delegates Sample Program
The delegate implementation can cause a great deal of confusion when encountered the first
time. Thus, it is a great idea to get an understanding by creating this sample program:

1 using System;
2
3 namespace Delegates
4 {
5 // Delegate Definition
6 public delegate int operation(int x, int y);
7
8 class Program
9 {
10 // Method that is passes as an Argument
11 // It has same signature as Delegates
12 static int Addition(int a, int b)
13 {
14 return a + b;
15 }
16
17 static void Main(string[] args)
18 {
19 // Delegate instantiation
20 operation obj = new operation(Program.Addition);
21
22
https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 3/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET
22
// output
23
Console.WriteLine("Addition is={0}",obj(23,27));
24
Console.ReadLine();
25
}
26
}
27
}

Here, we are defining the delegate as a delegate type. The important point to remember is that
the signature of the function reference by the delegate must match the delegate signature as:

1 // Delegate Definition
2 public delegate int operation(int x, int y);

Notice the format of the operation delegate type declaration; it specifies that the operation
object can permit any method to take two integers and return an integer. When you want to
insert the target methods to a given delegate object, pass in the name of the method to the
delegate constructor as:

1 // Delegate instantiation
2 operation obj = new operation(Program.Addition);

At this point, you can invoke the member pointed to using a direct function invocation as:

1 Console.WriteLine("Addition is={0}",obj(23,27));

Finally, when the delegate is no longer required, set the delegate instance to null.

Recall that .NET delegates are type-safe. Therefore, if you attempt to pass a delegate a method
that does not match the signature pattern, the .NET will report a compile-time error.
Array of Delegates
Creating an array of delegates is similar to declaring an array of any type. The following
example has a couple of static methods to perform specific math-related operations. Then you
use delegates to call these methods.

1 using System;
2
3 namespace Delegates
4 {
5 public class Operation
6 {
7 public static void Add(int a, int b)
8 {
9 Console.WriteLine("Addition={0}",a + b);
10 }
11
12 public static void Multiple(int a, int b)
13
https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 4/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

14 {
15 Console.WriteLine("Multiply={0}", a * b);
16 }
17 }
18
19 class Program
20 {
21 delegate void DelOp(int x, int y);
22
23 static void Main(string[] args)
24 {
25 // Delegate instantiation
26 DelOp[] obj =
27 {
28 new DelOp(Operation.Add),
29 new DelOp(Operation.Multiple)
30 };
31
32 for (int i = 0; i < obj.Length; i++)
33 {
34 obj[i](2, 5);
35 obj[i](8, 5);
36 obj[i](4, 6);
37 }
38 Console.ReadLine();
39 }
40 }
}

In this code, you instantiate an array of Delop delegates. Each element of the array is initialized
to refer to a different operation implemented by the operation class. Then, you loop through
the array and apply each operation to three different values. After compiling this code, the
output will be as follows;

Array of Delegates
Figure 1.2
Anonymous Methods
Anonymous methods, as their name implies, are nameless methods. They prevent the creation
of separate methods, especially when the functionality can be done without a new method
creation. Anonymous methods provide a cleaner and more convenient approach while coding.

Define an anonymous method with the delegate keyword and a nameless function body. This
code assigns an anonymous method to the delegate. The anonymous method must not have a
signature. The signature and return type is inferred from the delegate type. For example, if the

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 5/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

delegate has three parameters and returns a double type, the anonymous method would also
have the same signature.

1 using System;
2
3 namespace Delegates
4 {
5 class Program
6 {
7 // Delegate Definition
8 delegate void operation();
9
10 static void Main(string[] args)
11 {
12 // Delegate instantiation
13 operation obj = delegate
14 {
15 Console.WriteLine("Anonymous method");
16 };
17 obj();
18
19 Console.ReadLine();
20 }
21 }
22 }

The anonymous methods reduce the complexity of code, especially where several events are
defined. With the anonymous method, the code does not perform faster. The compiler still
defines methods implicitly.

Multicast Delegate
So far, you have seen a single method invocation/call with delegates. If you want to invoke/call
more than one method, you must make an explicit call through a delegate more than once.
However, it is possible for a delegate to do that via multicast delegates.

A multicast delegate is similar to a virtual container where multiple functions reference a stored
invocation list. It successively calls each method in FIFO (first in, first out) order. When you wish
to add multiple methods to a delegate object, you use an overloaded += operator rather than a
direct assignment.

1 using System;
2
3 namespace Delegates
4 {
5 public class Operation
6
https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 6/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET
6
{
7
public static void Add(int a)
8
{
9
Console.WriteLine("Addition={0}", a + 10);
10
}
11
public static void Square(int a)
12
{
13
Console.WriteLine("Multiple={0}",a * a);
14
}
15
}
16
class Program
17
{
18
delegate void DelOp(int x);
19
20
static void Main(string[] args)
21
{
22
// Delegate instantiation
23
DelOp obj = Operation.Add;
24
obj += Operation.Square;
25
26
obj(2);
27
obj(8);
28
29
Console.ReadLine();
30
}
31
}
32
}

The code above combines two delegates that hold the functions Add() and Square(). Here the
Add() method executes first and Square() later. This is the order in which the function pointers
are added to the multicast delegates.

To remove function references from a multicast delegate, use the overloaded -= operator that
allows a caller to remove a method from the delegate object invocation list dynamically.

1 // Delegate instantiation
2 DelOp obj = Operation.Add;
3 obj -= Operation.Square;

Here when the delegate is invoked, the Add() method is executed, but Square() is not because
we unsubscribed it with the -= operator from a given runtime notification.

Invoking multiple methods by one delegate may lead to a problematic situation. If one of the
methods invoked by a delegate throws an exception, the complete iteration would be aborted.
You can avoid such a scenario by iterating the method invocation list. The Delegate class
defines a method GetInvocationList that returns an array of Delegate objects.
https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 7/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

1 using System;
2
3 namespace Delegates
4 {
5 public class Operation
6 {
7 public static void One()
8 {
9 Console.WriteLine("one display");
10 throw new Exception("Error");
11 }
12 public static void Two()
13 {
14 Console.WriteLine("Two display");
15 }
16 }
17
18 class Program
19 {
20 delegate void DelOp();
21
22 static void Main(string[] args)
23 {
24 // Delegate instantiation
25 DelOp obj = Operation.One;
26 obj += Operation.Two;
27
28 Delegate[] del = obj.GetInvocationList();
29
30 foreach (DelOp d in del)
31 {
32 try
33 {
34 d();
35 }
36 catch (Exception)
37 {
38 Console.WriteLine("Error caught");
39 }
40 }
41 Console.ReadLine();
42 }
43 }
44 }

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 8/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

When you run the application, you will see that the iteration continues with the next method
even after an exception is caught, as in the following.

Multicast Delegate
Figure 1.3
Events
The applications and windows communicate via predefined messages. These messages contain
various information to determine window and application actions. The .NET considers these
messages as an event. You will handle the corresponding event if you need to react to a specific
incoming message. For instance, when a button is clicked on a form, Windows sends a
WM_MOUSECLICK message to the button message handler.

You don't need to build custom methods to add or remove methods to a delegate invocation
list. C# provides the event keyword. When the compiler processes the event keyword, you can
subscribe and unsubscribe methods and any necessary member variables for your delegate
types. The syntax for the event definition should be as in the following:

Accessibility event delegatename eventname;

Defining an event is a two-step process. First, you need to define a delegate type that will hold
the list of methods to be called when the event is fired. Next, you declare an event using the
event keyword. To illustrate the event, we are creating a console application. In this iteration,
we will define an event to add that is associated with a single delegate DelEventHandler.

1 using System;
2
3 namespace Delegates
4 {
5 public delegate void DelEventHandler();
6
7 class Program
8 {
9 public static event DelEventHandler add;
10
11 static void Main(string[] args)
12 {
13 add += new DelEventHandler(USA);
14 add += new DelEventHandler(India);
15 add += new DelEventHandler(England);
16 add.Invoke();
17
18 Console.ReadLine();
19 }
20 static void USA()
21
https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 9/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

22 {
23 Console.WriteLine("USA");
24 }
25
26 static void India()
27 {
28 Console.WriteLine("India");
29 }
30
31 static void England()
32 {
33 Console.WriteLine("England");
34 }
35 }
}

In the main method, we associate the event with its corresponding event handler with a
function reference. Here, we fill the delegate invocation lists with a couple of defined methods
using the +=operator. Finally, we invoke the event via the Invoke method.

Note: Event Handlers can't return a value. They are always void.

Let's use another example to get a better understanding of events. Here we are defining an
event name as xyz and a delegate EventHandler with a string argument signature in the
operation class. We are putting the implementation in the action method to confirm whether
an event is fired or not.

1 using System;
2
3 namespace Delegates
4 {
5 public delegate void EventHandler(string a);
6
7 public class Operation
8 {
9 public event EventHandler xyz;
10
11 public void Action(string a)
12 {
13 if (xyz != null)
14 {
15 xyz(a);
16 Console.WriteLine(a);
17 }
18 else
19
https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 10/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET
19
{
20
Console.WriteLine("Not Registered");
21
}
22
23 }
24 }
25
26 class Program
27 {
28 public static void CatchEvent(string s)
{
29
Console.WriteLine("Method Calling");
30
}
31
32
33 static void Main(string[] args)
34 {
35 Operation o = new Operation();
36
37 o.Action("Event Calling");
o.xyz += new EventHandler(CatchEvent);
38
39
40 Console.ReadLine();
41 }
}
42
}

Later in the Program class, we are defining a CatchEvent method that would be referenced in
the delegate invocation list. Finally, we instantiated the operation class and implemented the
event firing in the main method.

Finally, we are elaborating on the events with a realistic example of creating a custom button
control over the Windows form that would be called from a console application. First, we inherit
the program class from the Form class and define its associated namespace at the top. Then,
we craft a custom button control in the program class constructor.

1 using System;
2 using System.Drawing;
3 using System.Windows.Forms;
4
5 namespace Delegates
6 {
7 //custom delegate
8 public delegate void DelEventHandler();
9
10 class Program :Form
11 {
12
https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 11/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET
12
13 //custom event
14 public event DelEventHandler add;
15
16 public Program()
17 {
18 // desing a button over form
Button btn = new Button();
19
btn.Parent = this;
20
btn.Text = "Hit Me";
21
btn.Location = new Point(100,100);
22
23
//Event handler is assigned to
24
// the button click event
25
btn.Click += new EventHandler(onClcik);
26
add += new DelEventHandler(Initiate);
27
28
//invoke the event
29
add();
30
31 }
32 //call when event is fired
33 public void Initiate()
34 {
35 Console.WriteLine("Event Initiated");
36 }

37
//call when button clicked
38
public void onClcik(object sender, EventArgs e)
39
{
40
MessageBox.Show("You clicked me");
41
}
42
static void Main(string[] args)
43
{
44
Application.Run(new Program());
45
46
Console.ReadLine();
47
}
48
49 }
50
}

We call the Windows Form using the Run method of the Application class. Finally, when the user
runs this application, the Event fired message will be displayed on the screen, and a Windows
Form with the custom button control will be displayed. When the button is clicked, a message
box will be shown as in the following;

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 12/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

Figure4.jpg
Figure 1.4

Summary

This article taught us about delegates and events in C# and .NET.

Delegates in C# Events Events C# .NET Multicast Delegate

RECOMMENDED FREE EBOOK

Programming C# for Beginners

Download Now!

SIMILAR ARTICLES

Vidya Vrat Agarwal


I am a Principal Software Engineering Manager in the Microsoft Azure-CXP team. I am a
Software Architect, Author, Technical Reviewer, Blogger, Speaker, and a Mentor. I am an Ex-
Microsoft MVP, and a C# Corner MVP. I am a... Read more
http://www.mypassionfor.net

NA 12.4m 6 7

View All Comments


47

Type your comment here and press Enter Key (Minimum 10 characters)

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 13/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

About Us Contact Us Privacy Policy Terms Media Kit Sitemap Report a Bug FAQ Partners

C# Tutorials Common Interview Questions Stories Consultants Ideas Certifications Sharp TV

Web3 Universe Build with JavaScript Let's React DB Talks Jumpstart Blockchain Interviews.help
©2024 C# Corner. All contents are copyright of their authors.

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 14/15
5/10/24, 4:25 PM Mastering Delegates and Events In C# .NET

https://www.c-sharpcorner.com/UploadFile/84c85b/delegates-and-events-C-Sharp-net/ 15/15

You might also like