Dot Net For All

Create and Invoke C# Delegate

In C# programming delegate is most confusing topic and all the new programmers find it difficult to remember the syntax to create and invoke C# delegate.

You may find below article helpful before proceeding:

Delegates in C#, Why do we need C# delegates, Action Func and predicate in C#

Create C# Delegate

As mentioned in one of my article delegate is a reference type and CLR converts delegate into a class while converting it into IL.

Action Func and Predicate were introduced in the C# 2.0. And it helped us not to create our own delegate every time we need one. Though we can create C# delegate if any of these existing one delegate are not as per our need.

Lets see how we can create our first simple delegate using one of predefined delegates.

  private Action<int> func;
        public Program()
        {
            func = MyMethod;
            for (int i = 0; i < 10; i++)
            {
                func(10);
            }
        }

        private void MyMethod(int obj)
        {
            Console.WriteLine(obj);
        }

The above code uses a Action delegate. The method pointer should take a single parameter. That is what MyMethod does.

And I am invoking the func delegate in the for loop to print the numbers.

The other better and concise way to write and use the above delegate is shown in the below code. In the below code I have replaced MyMethod with a lambda expression.

 private Action<int> func = new Action<int>(x => Console.WriteLine(x));
        public Program()
        {           
            for (int i = 0; i < 10; i++)
            {
                func(10);
            }
        }

We should be aware that where ever we are expecting a delegate as parameter for a method. We can pass a method with same signature as delegate.

As an example Array.ForEach method expects first parameter as an array and second parameter as an Action<int> delegate as shown in below code.

public static void ForEach<T> (T[] array, Action<T> action);

Therefore we can call the above method just by passing the method pointer or more simply just by passing a lambda expression.

int[] arr1 = {1,2,3,4,5}; 
Array.ForEach(arr1, x => Console.WriteLine(x));

There are three ways to create a C# delegate:

First is to create our own delegate and instantiate it by providing with the method we need to call as shown in the figure below. We should be careful here, is any one of the existing Func, Action or Predicate is serving the purpose we can use it.

private delegate int MyDelegate(int a);        
MyDelegate del = new MyDelegate(MyMethod);<br>        
private static int MyMethod(int a){            return 0;        }

The second way to create a delegate is create a variable and assign the method to it.

private delegate int MyDelegate(int a);
MyDelegate del = MyMethod;
private static int MyMethod(int a){            return 0;        }

And finally we can use any of the already existing delegates as shown in the above code examples.

Invoke C# delegate

Once we are done with the creation of the delegate we can invoke it as well.

In the above code example I have created my custom delegate named del.

To invoke the delegate I can call the del variable by providing the same parameters as MyDelegate expects. See the code below.

 int test = del(0);

Once the above code is executed, the references method will be called and executed. And since the method returns some numeric value we can assign it to a variable.

The other way to invoke a delegate is using the Invoke method provided by delegate class. Using Invoke we can synchronously call the referenced method.

int test = del.Invoke(100);

Finally we can simply pass a method as parameter to another method where ever it is expecting a delegate. The same I have shown in the code above where ForEach expects an Action<int> delegate.

Conclusion:

In this article I have shown you the different ways to create and invoke C# delegate with code examples. I hope this article will help to have a better understanding of the delegates in C#.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview