Delegates in C#

Delegates in C# with Examples

In this article, I am going to discuss the Delegates in C# with some real-time examples. As part of this article, we are going to discuss the following important concepts in detail.

  1. What are delegates in C#?
  2. How many ways we can call a method in C#?
  3. How to invoke methods using delegates in C#?
  4. Examples of using Delegates.
  5. Rules of using Delegates in C#.
  6. What are the types of delegates?
What are delegates in C#?

In simple word, we can say that the delegates in C# are the Type-Safe Function Pointer. It means they hold the reference of a method and then calls that method for execution.

How many ways we can call a method in C#?

In C#, we can call a method that is defined in a class in two ways are as follows. We can call the method using the object of the class if it is a non-static method or we can call the method through class name if it is a static method.

We can also call a method by using delegates in C#. Calling a method using delegate will be faster in execution as compared to the first process i.e. either by using an object or by using the class name.

Let’s first see the first approach to call the methods of a class
namespace DelegateDemo
{
    public class Program
    {
        //NonStatic method
        public void Add(int x, int y)
        {
            Console.WriteLine(@"The Sum of {0} and {1}, is {2} ", x, y, (x + y));
        }

        //Static Method
        public static string Greetings(string name)
        {
            return "Hello @" + name;
        }

        static void Main(string[] args)
        {
            Program obj = new Program();

            //calling non static method through object
            obj.Add(100, 100);

            //Calling static method with class name
            string GreetingsMessage = Program.Greetings("Pranaya");
            Console.WriteLine(GreetingsMessage);
            Console.ReadKey();
        }
    }
}

OUTPUT:

Delegates in C#

In the above example, we are calling the methods using object and class name. Now let’s see how to call a method using delegates in C#.

How to invoke methods using delegates in C#?

If you want to invoke or call a method using delegates then you need to follow three simple steps.  The steps are as follows.

  1. Defining a delegate
  2. Instantiating a delegate
  3. Invoking a delegate
Step1: Define a delegate.

The syntax for defining a delegate: <Access Modifier> delegate <return type> <delegate name> (arguments list);

Example1: If you have a method like below.

public void Add(int x, int y)
{
    Console.WriteLine(@"The Sum of {0} and {1}, is {2} ", x, y, (x + y));
}

Then you have to define a delegate like public delegate void AddDelegate(int a, int b);

Example2: If you have a method like below

public static string Greetings(string name)
{
     return "Hello @" + name;
}

Then you need to define a delegate like below

public delegate string GreetingsDelegate(string name);

Note: The point that you need to remember is the signature of the delegate and the method it points should be same. So, when you create a delegate in C#, then the access modifier, return type, number of arguments and their data types of the delegates must and should be same as the access modifier, return type, number of arguments and the data types of the function that the delegate wants to refer.

You can define the delegates either within a class or just like other types we defined under a namespace.

Step2: Instantiating the Delegate.

To consume the delegate you must first create an object of the delegate and while creating the object the method you want to execute using the delegate should be passed as a parameter.

Syntax:

Delegate Name Object Name = new Delegate Name (target function name);

Example:

AddDelegate ad = new AddDelegate(obj.Add);

GreetingsDelegate gd = new GreetingsDelegate(Program.Greetings);

Note: Generally we create the objects under the Main() method of a class. So while binding the method with delegate if the method is non-static refer to it as the object of the class and if it is static refer to it with the name of the class.

Step3: Invoking the delegate.

Now call the delegate by supplying the required values to the parameters so that the methods get executed internally which is bound with the delegates.

For example:

ad(100, 50);

ad.Invoke(200, 300);

string GreetingsMessage = gd(“Priyanka”);

string GreetingsMessage = gd.Invoke(“Anurag”);

At this point, the function that is referred by the delegate will be called for execution.

Complete example for a better understanding.
namespace DelegateDemo
{
    //Defining Delegates
    //Note: The access specifeis, return type and the number, order and type of parameters of delegate
    //should be same as the function it refers to.
    public delegate void AddDelegate(int a, int b);
    public delegate string GreetingsDelegate(string name);

    public class Program
    {
        //Defining Methods
        //NonStatic method
        public void Add(int x, int y)
        {
            Console.WriteLine(@"The Sum of {0} and {1}, is {2} ", x, y, (x + y));
        }

        //Static Method
        public static string Greetings(string name)
        {
            return "Hello @" + name;
        }

        static void Main(string[] args)
        {
            Program obj = new Program();

            //Instantiating delegate by passing the target function Name
            //The Add method is non static so here we are calling method using object
            AddDelegate ad = new AddDelegate(obj.Add);

            //Greetings method is static so here we are callling the method by using the class name
            GreetingsDelegate gd = new GreetingsDelegate(Program.Greetings);

            //Invoking The Delegates
            ad(100, 50);
            string GreetingsMessage = gd("Pranaya");

            //We can also use Invoke method to execute delegates
            // ad.Invoke(100, 50);
            // string GreetingsMessage = gd.Invoke("Pranaya");
            Console.WriteLine(GreetingsMessage);
            Console.ReadKey();
        }
    }
}

When you run the application, it will give you the following output.

Delegates in C#

Rules of using Delegates in C#:
  1. A delegate is also a user-defined type and before invoking a method using delegate we must have to define that delegate first.
  2. The signature of the delegate must match the signature of the method, the delegate points to otherwise we will get a compiler error. This is the reason why delegates are called as type-safe function pointers.
  3. A Delegate is similar to a class. Means we can create an instance of a delegate and when we do so, we need to pass the method name as a parameter to the delegate constructor, and it is the function the delegate will point to
  4. Tip to remember delegate syntax: Delegates syntax look very much similar to a method with a delegate keyword.
What are the types of delegates?

The Delegates are classified into two types such as

  1. Single cast delegate
  2. Multicast delegate

If a delegate is used for invoking a single method then it is called a single cast delegate or unicast delegate. In other words, we can say that the delegates that represent only a single function are known as single cast delegate.

If a delegate is used for invoking multiple methods then it is known as the multicast delegate. OR the delegates that represent more than one function are called Multicast delegate.

The example that we discussed in this article is of type Single cast delegate because the delegate points to a single function.

In the next article, I am going to discuss the Multicast Delegate in C# with some examples. Here, in this article, I try to explain Delegates in C# with some examples. I hope you understood the need and how to use delegates in C#.

Leave a Reply

Your email address will not be published. Required fields are marked *