Delegates and events in C#

C# delegates are just like function pointers in C++. In C#, delegate is a reference type data and it holds the reference of a method.The reference can be changed at runtime.

C# Delegate, contains the reference to several methods and call them when needed. So, you create numbers of methods as you need and attach it to delegates. At runtime, an event gets fired and delegates dynamically call the function and show the result.

All the delegates are implicitly derived from System.Delegate class.

Syntax to declare delegates

<access_modifiers> delegate <return type> <delegate-name> (parameter list)

Delegate example

Let's consider a delegate example. Suppose, we want to do 2 operations, Add or subtract 2 numbers, then we will create two 

using System;

//create a static class with static methods
public static class MathDelegate
{
    public static double MultipleByTwo(double value)
    {
        return value * 2;
    }

    public static double Square(double value)
    {

        return value * value;

    }
	
 
}

//declared delegate
public delegate double DoubleOp(double x);

public class DelegateExampleInCsharp
{
    public static void Main()
    {
		//call multiple by two
        DoubleOp operations =MathDelegate.MultipleByTwo;           
        var result = operations(5.2);
        Console.WriteLine("Multiple By Two="+result);
      
       //call square the number
        operations =MathDelegate.Square;           
        result = operations(5.2); //this time value will be multiples by itself
        Console.WriteLine("Sqaure results="+result);
       	     
    }  

}

In the above code, we have created a delegate, "DoubleOp", and have created a static class "MathDelegate", which contains two static methods, one is used Multiply the value by 2 and second multiple the value by itself.

If you will notice the above code, we have created one variable "operations" of delegate "DoubleOp" type, by providing the function name, output result changes, as method to be called is decided at runtime by assigning it's value to "operations".

Output:

Multiple By Two=10.4
Sqaure results=27.04

You can run the above code or plat with it using below fiddle.

Delegate can also be multicast delegate.

In multicast delegate, the delegate can points to multiple methods. Multicast delegate is a delegate which holds a reference to more than one method. The "+" operator adds a function to the delegate object and the "-" operator removes an existing function from a delegate object.

Refer: Understanding Delegates in C# with examples (with Multicast delegate)

C# Events

An event in a very simple language is an action or occurrence, such as clicks, key press, mouse movements, or system generated notifications. Application can respond to events when they occur. Events are messages sent by the object to indicate the occurrence of the event. Events are an effective mean of 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 other classes.

Events are part of a class and the same class is used to publish its events. Events use the publisher and subscriber model.

A publisher is an object that contains the definition of the event and the delegate. The association of the event with the delegate is also specified in the publisher class. The object of the publisher class invokes the event, which is notified to the other objects. A subscriber is an object that wants to accept the event and provide a handler to the event. The delegate of the publisher class invokes the method of the subscriber class. This method in the subscriber class is the event handler. The publisher and subscriber model implementation can be defined by the same class.

event-delegates-c-sharp-min.png

Event example

First we will create a "publisher" class where we will define delegate and event to be called

//Define class as Publisher
public class Publisher
{
    //OnChange property containing all the 
    //list of subscribers callback methods
    public event Action OnChange = delegate { };

    public void RaiseChangeEvent()
    {
        //Invoke OnChange Action
        OnChange();
    }
}

Now, we will use above event-delegate class in our main application, by creating "publisher" class object and then registering OnChange event.

public class Program
{
	public static void Main()
	{
		 //Initialize publisher class object
        Publisher pub = new Publisher();

        //register for OnChange event - Subscriber 1
        pub.OnChange += () => Console.WriteLine("Subscriber 1 Called");
        //register for OnChange event - Subscriber 2
        pub.OnChange += () => Console.WriteLine("Subscriber 2 Called");

        //raise the event
        pub.RaiseChangeEvent();

        //After this RaiseChangeEvent() method is called
        //all subscribers callback methods will get invoked
		//and will print string mentioned inside it
	}
}

Output:

Subscriber 1 Called
Subscriber 2 Called

You can try it in below fiddle


Share Tweet