C# Basics: Delegates

Delegates are one of the most used features of C#. It allows you to pass a function as of function pointer. It is kind of same as function pointer of C++.

Put simply, delegates are the same as a function pointer of C ++. It refers to another function.

As noted in Microsoft official documentation:

“A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.”

Before get deeper into technical jargon about delegates, let us create first a delegate.


// declaring a delegate
public delegate int AddDelegate(int num1, int num2); // 1
static void Main(string[] args)
{
AddDelegate d1 = new AddDelegate(add); // 2
int result = d1(7, 2); // 3
Console.WriteLine(result);
Console.ReadKey(true);
}
public static int add(int a, int b) // function
{
Console.WriteLine(" A Delegate Called me");
int res;
res = a + b;
return res;
}

view raw

delegate1.cs

hosted with ❤ by GitHub

Let us talk through the above code.

  1. Just before main function in comment #1, we are declaring a delegate named AddDelegate. The signature of a delegate is very important, because a delegate can only refer functions matching the same signature.
  2. We created delegate with return type set to integer and it takes two input integer parameters.
  3. In comment # 2, we are instantiating delegate and passing add function as reference.
  4. In comment # 3 invoking the delegate.

On running above, you should get output as shown in the below image:

One important thing you need to keep in mind is that the signature of delegates must match with the signature of the function pointed by the delegate. Not only signature, but also return type should match.

Read full article on the Infragistics blog

Leave a comment

Create a website or blog at WordPress.com