C# Delegates and Events

The Delegate type represents a delegate in C#. Delegates in C# are used to invoke methods at runtime. A Delegates in .NET can be a singlecast delegate or a multicast delegate. This tutorial with code examples explain how to instantiate a delegate, reference a delegate, and call a delegate in C# and .NET.

 Delegates In C#
 
Delegates and events are a fundamental concept yet complex in .NET and C# language. This article explains basic concepts of delegates and events and how they are used in a .NET and C# application.
 

Delegates

 
Delegate is one of the base types in .NET. Delegate is a class, which is used to create and invoke delegates at runtime.
 
C# Delegates
 
Delegate in C# is similar to a function pointer in C or C++. It's a new type of object in C#. Delegate is very special type of object as earlier the entire the object we used to defined contained data but delegate just contains the details of a method.
 

Need of delegate

 
Programmers often needs to pass a method as a parameter of other methods. For this purpose we create and use delegates.
A delegate is a class that encapsulates a method signature. Although it can be used in any context, it often serves as the basis for the event-handling model in C# and .NET.
 
One good way of understanding delegates is by thinking of a delegate as something that gives a name to a method signature.
 
Example:
  1. public delegate int DelegateMethod(int x, int y);  
Any method that matches the delegate's signature, which consists of the return type and parameters, can be assigned to the delegate.
 
This makes is possible to programmatically change method calls, and also plug new code into existing classes. As long as you know the delegate's signature, you can assign your own-delegated method.
 
This ability to refer to a method as a parameter makes delegates ideal for defining callback methods.
 
Delegate magic
 
In class we create its object, which is instance, but in delegate when we create instance that is also referred as delegate (means whatever you do you will get delegate).
 
Delegate does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.
 

Benefits of delegates

 
In simple words delegates are object oriented and type-safe and very secure as they ensure that the signature of the method being called is correct. Delegates makes event handling simple and easy.
 

Types of delegates

 
There are two types of delegates, singlecast delegates, and multiplecast delegates.
 
Singlecast delegate
 
Singlecast delegate point to single method at a time. In this the delegate is assigned to a single method at a time. They are derived from System.Delegate class.
 
Multicast Delegate
 
When a delegate is wrapped with more than one method that is known as a multicast delegate.
 
In C#, delegates are multicast, which means that they can point to more than one function at a time. They are derived from System.MulticastDelegate class.
 
Defining and using delegates 
 
There are three steps in defining and using delegates:
 
1. Declaration
 
To create a delegate, you use the delegate keyword.
  1. [attributes] [modifiers] delegate ReturnType Name ([formal-parameters]);  
  • The attributes factor can be a normal C# attribute.
  • The modifier can be one or an appropriate combination of the following keywords: new, public, private, protected, or internal.
  •  The ReturnType can be any of the data types we have used so far. It can also be a type void or the name of a class.
  •  The Name must be a valid C# name. 
Because a delegate is a definituon for a method, you must use parentheses, required for every method. If this method will not take any argument, leave the parentheses empty.
 
Example:
  1. public delegate void DelegateExample();  
The above code is how a delegate with no papameters is defined.
 
2. Instantiation
  1. DelegateExample d1 = new DelegateExample(Display);  
The above code shows how a delegate is initiated.
 
3. Invocation 
  1. d1();  
The above code piece invokes a delegate d1().
 
Program to demonstrate Singlecast delegate
 
Here is a sample code that demonstrates how to create and use a singlecast delegate.
  1. using System;    
  2. namespace ConsoleApplication5    
  3. {    
  4. class Program    
  5. {    
  6. public delegate void delmethod();    
  7.   
  8. public class P    
  9. {  
  10.   
  11. public static void display()    
  12. {    
  13. Console.WriteLine("Hello!");    
  14. }    
  15.   
  16. public static void show()    
  17. {    
  18. Console.WriteLine("Hi!");    
  19. }    
  20.   
  21. public void print()
  22. {
  23. Console.WriteLine("Print");
  24. }

  25. }
  26.   
  27. static void Main(string[] args)
  28. {
  29. // here we have assigned static method show() of class P to delegate delmethod()
  30. delmethod del1 = P.show;
  31.   
  32. // here we have assigned static method display() of class P to delegate delmethod() using new operator
  33. // you can use both ways to assign the delagate
  34. delmethod del2 = new delmethod(P.display);
  35. P obj = new P();
  36.   
  37. // here first we have create instance of class P and assigned the method print() to the delegate i.e. delegate with class    
  38. delmethod del3 = obj.print;
  39.   
  40. del1();
  41. del2();
  42. del3();
  43. Console.ReadLine();
  44. }
  45. }
  46. }
Program to demonstrate Multicast delegate
 
Here is sample code that demonstrates how to create and use a multicast delegate.
  1. using System;  
  2. namespace delegate_Example4  
  3. {  
  4.   
  5. class Program  
  6. {  
  7. public delegate void delmethod(int x, int y);  
  8.   
  9. public class TestMultipleDelegate  
  10. {  
  11. public void plus_Method1(int x, int y)  
  12. {  
  13. Console.Write("You are in plus_Method");  
  14. Console.WriteLine(x + y);  
  15. }  
  16.   
  17. public void subtract_Method2(int x, int y)  
  18. {  
  19. Console.Write("You are in subtract_Method");  
  20. Console.WriteLine(x - y);  
  21. }  
  22. }  
  23.   
  24. static void Main(string[] args)  
  25. {  
  26.   
  27. TestMultipleDelegate obj = new TestMultipleDelegate();  
  28. delmethod del = new delmethod(obj.plus_Method1);  
  29.   
  30. // Here we have multicast  
  31. del += new delmethod(obj.subtract_Method2);  
  32. // plus_Method1 and subtract_Method2 are called  
  33. del(50, 10);  
  34. Console.WriteLine();  
  35. //Here again we have multicast  
  36. del -= new delmethod(obj.plus_Method1);  
  37. //Only subtract_Method2 is called  
  38. del(20, 10);  
  39. Console.ReadLine();  
  40. }  
  41. }  
  42. }  
Point to remember about Delegates:
  • Delegates are similar to C++ function pointers, but are type safe.
  • Delegate gives a name to a method signature.
  • Delegates allow methods to be passed as parameters.
  • Delegates can be used to define callback methods.
  • Delegates can be chained together; for example, multiple methods can be called on a single event.
  • C# version 2.0 introduces the concept of Anonymous Methods, which permit code blocks to be passed as parameters in place of a separately defined method.
  • Delegate helps in code optimization.
  • Usage areas of delegates
The most common example of using delegates is in events. 
  • They are extensively used in threading
  • Delegates are also used for generic class libraries, which have generic functionality, defined.

Anonymous Delegates

 
You can create a delegate, but there is no need to declare the method associated with it. You do not have to explicitly define a method prior to using the delegate. Such a method is referred to as anonymous. In other words, if a delegate itself contains its method definition it is known as anonymous method.
 
The code is an example of using an anonymous delegate.
  1. using System;  
  2.   
  3. public delegate void Test();  
  4.   
  5. public class Program  
  6. {  
  7. static int Main()  
  8. {  
  9. Test Display = delegate()  
  10. {  
  11. Console.WriteLine("Anonymous Delegate method");  
  12. };  
  13.   
  14. Display();  
  15. return 0;  
  16. }  
  17. }  
Note: You can also handle event in anonymous method.
 

Events

 
Events and delegate work together. An event is a reference to a delegate i.e. when an event is raised, a delegate is called. In C# terms, events are a special form of delegates. 
 
Events play an important part in user interfaces and programming notifications. Events and delegates work hand-in-hand to provide a communication between code from one class to other class. When something happens in one class or one part of the code and other part of the code needs a notification, events are used. 
 
A C# event is a class member that is activated whenever the event it was designed for occurs. It starts with a class that declares an event. Any class, including the same class that the event is declared in, may register one of its methods for the event. This occurs through a delegate, which specifies the signature of the method that is registered for the event. The event keyword is a delegate modifier. It must always be used in connection with a delegate.
 
The delegate may be one of the pre-defined .NET delegates or one you declare yourself. Whichever is appropriate, you assign the delegate to the event, which effectively registers the method that will be called when the event fires.
 

How to use events in C#?

 
Once an event is declared, it must be associated with one or more event handlers before it can be raised. An event handler is nothing but a method that is called using a delegate. Use the += operator to associate an event with an instance of a delegate that already exists.
 
Example:
  1. obj.MyEvent += new MyDelegate(obj.Display);  
An event has the value null if it has no registered listeners.
 
Although events are mostly used in Windows controls programming, they can also be implemented in console, web and other applications.
 
Program for creating a custom Singlecast delegate and event
  1. using System;  
  2. namespace delegate_custom  
  3. {  
  4. class Program  
  5. {  
  6. public delegate void MyDelegate(int a);  
  7.   
  8. public class XX  
  9. {  
  10. public event MyDelegate MyEvent;  
  11.   
  12. public void RaiseEvent()  
  13. {  
  14. MyEvent(20);  
  15. Console.WriteLine("Event Raised");  
  16. }  
  17.   
  18. public void Display(int x)  
  19. {  
  20. Console.WriteLine("Display Method {0}", x);  
  21. }  
  22. }  
  23.   
  24. static void Main(string[] args)  
  25. {  
  26.   
  27. XX obj = new XX();  
  28. obj.MyEvent += new MyDelegate(obj.Display);  
  29.   
  30. obj.RaiseEvent();  
  31. Console.ReadLine();  
  32. }  
  33. }  
  34. }  
Program for creating custom a multiplecast delegate and event
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5.   
  6. namespace delegate_custom_multicast  
  7. {  
  8. class Program  
  9. {  
  10. public delegate void MyDelegate(int a, int b);  
  11.   
  12. public class XX  
  13. {  
  14. public event MyDelegate MyEvent;  
  15.   
  16. public void RaiseEvent(int a, int b)  
  17. {  
  18. MyEvent(a, b);  
  19. Console.WriteLine("Event Raised");  
  20. }  
  21.   
  22. public void Add(int x, int y)  
  23. {  
  24. Console.WriteLine("Add Method {0}", x + y);  
  25. }  
  26.   
  27. public void Subtract(int x, int y)  
  28. {  
  29. Console.WriteLine("Subtract Method {0}", x - y);  
  30. }  
  31. }  
  32.   
  33. static void Main(string[] args)  
  34. {  
  35.   
  36. XX obj = new XX();  
  37. obj.MyEvent += new MyDelegate(obj.Add);  
  38. obj.MyEvent += new MyDelegate(obj.Subtract);  
  39. obj.RaiseEvent(20, 10);  
  40. Console.ReadLine();  
  41. }  
  42. }  
  43. }  
Conclusion
 
Hope the article would have helped you in understanding delegates and events.
 
Here is another recommended article on Delegates in C#.