Signup/Sign In
LAST UPDATED: SEPTEMBER 15, 2021

C# Delegates and Events

    This tutorial introduces the innovative feature of C# programming language: Delegates and Events. The delegates and events are related concepts as an event is built upon a delegate. In the subsequent section of this tutorial, we will be looking at this concept with practical examples.

    C#: Delegates

    A delegate is an object or a type that can refer to a method (holds a reference to a method). This concept is similar to function pointers in C/C++ programming language. A delegate holds references only to those methods whose signature (parameter list) matches with the delegate. A delegate is useful when you want to pass a function as a parameter, and which can be achieved by declaring a delegate using delegate keyword followed by a function signature. The syntax to declare a delegate is shown here:

    <access_specifier> delegate <return_type> <delegate_name>(parameters_list);

    Note: All the delegates are derived from the System.Delegate class. Also, delegates can hold multiple references for methods, and they are called as multicast.

    Let's see the very basic example of a delegate.

    Filename: Program.cs

    using System;
    
    namespace Studytonight
    {
        // declare a delegate
        public delegate void DelegateEx();
    
        public class Program
        {
            public static void display()
            {
                Console.WriteLine("Hello, World!");
            }
            public static void Main(string[] args)
            {
                DelegateEx dx = new DelegateEx(display);
                dx();
            }
        }
    }

    Output:

    Hello, World!

    In the above example, we have declared a delegate using the delegate keyword but with no parameter list and no return type. Furthermore, we have defined a method that prints text on a console. In the main section of the program, we have given a reference of the display method by creating the object of delegate class. In last, we invoked the object, and hence the desired output got printed on the console.

    Note: The method invoked by a delegate is determined at run-time, not at compile-time.

    Let's take another example of delegate with signature and return type.

    Filename: Program.cs

    using System;
    namespace Studytonight
    {
        public delegate double deposit(double amt);
        public class Program
        {
            public static double Amount(double new_amount)
            {
                double previous_amount = 2193.56;
                return previous_amount + new_amount;
            }
            public static void Main(string[] args)
            {
                deposit d = new deposit(Amount);
                Console.WriteLine("Total Bank Balance: "+d(5000));
            }
        }
    }

    Output:

    Total Bank Balance: 7193.56

    The above example is similar to the previous example except with the parameter and return type.


    C#: Multicast Delegate

    Multicasting is one of the advantages and important features of a delegate. A delegate that holds more than one reference of methods at a time is referred to as a multicast delegate. In simple words, multicasting is the ability to create an invocation list of methods which will get called when a delegate is invoked. If you want to add multiple methods in the invocation list, then use + or += operator and to remove, use - or -= operator. Following is the demonstration of multicasting:

    Filename: Program.cs

    using System;
    namespace Studytonight
    {
        public class BankOperations
        {
            public static double previous_amount = 2193.56;
            public static void Deposit(double new_amount)
            {
                previous_amount += new_amount;
                Console.WriteLine("Current Bank Balance: "+previous_amount);
            }
            public static void Reward(double new_amount)
            {
                if(new_amount >= 5000)
                {
                    double bonus = 500;
                    Console.WriteLine("Bonus Applied, Bank Balance: "+(previous_amount+bonus));
                }            else
                {
                    Console.WriteLine("No Bonus Applied");
                }
            }
        }
        public class Program
        {
            public delegate void BankDelegate(double amt);
            public static void Main(string[] args)
            {
                BankDelegate bd = BankOperations.Deposit;
                bd += BankOperations.Reward;
                bd(5000);
            }
        }
    }

    Output:

    Current Bank Balance: 7193.56
    Bonus Applied, Bank Balance: 7693.56

    In the above multicasting example, we have combined two delegates that hold the reference of Deposit and Reward methods. Firstly, the Deposit method gets executed, then the Reward method, which means the order in which you added the methods in the invocation list gets executed accordingly. If you observe closely, to add the references of multiple methods, we used += operator. We hope this basic example helped you to understand the concept of multicasting.


    C#: Events

    An event is an occurrence of a particular action. It can occur when you press the keyboard key, mouse clicks or movements, etc. Events are built upon the foundation of delegates hence they are co-related. Moreover, events are based on the publisher-subscriber model, which means when a class raises an event its called publisher, whereas when a class receives or handles the event, its called subscriber.

    Events are members of a class and are declared using the event keyword. The syntax to declare an event is shown here:

    public delegate void EventName();
    
    public event EventName EN;

    Here, the EventName is the name of delegate used to support an event, and EN is the name of the event object.

    Note: Events are based on the EventHandler delegate and the EventArgs base class. Also, the event handlers can't return a value. They are always of void return type.

    Let's take a simple example of an event

    Filename: Program.cs

    using System;
    namespace Studytonight
    {
        public class Program
        {
            public delegate void DelegateEventHandler();
            public static double previous_amount = 2193.56;
            public static void Deposit()
            {
                Console.WriteLine("Current Bank Balance: "+previous_amount);
            }
            public static void Reward()
            {
                if(previous_amount >= 5000)
                {
                    double bonus = 500;
                    Console.WriteLine("Bonus Applied, Bank Balance: "+(previous_amount+bonus));
                }            
                else
                {
                    Console.WriteLine("No Bonus Applied");
                }
            }
            public static event DelegateEventHandler deh;
            public static void Main(string[] args)
            {
                deh += new DelegateEventHandler(Deposit);
                deh += new DelegateEventHandler(Reward);
                deh.Invoke();
            }
        }
    }

    Output:

    Total Bank Balance: 2193.56
    No Bonus Applied

    In the above event example, similar to the delegate example, we have added the references of methods in the invocation list and then we invoked an event using the invoke method. As we know, event handlers can't return a value and hence they are void.

    We hope this tutorial helped you to understand the concept of delegates and events in C# programming.

    You may also like:

    Subject Matter Expert of C# Programming at Studytonight.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS