Thursday, April 12, 2012

Delegates in c#

I have used delegates in my programming since C# 2.0. But I have seen there are lots of confusion going on with delegates so I have decided to blog about it. In this blog I will explain about delegate basics and use of delegates in C#.

What is delegate?

We can say a delegate is a type safe function pointer which holds methods reference in object. As per MSDN it's a type that references to a method. So you can assign more than one methods to delegates with same parameter and same return type.

Following is syntax for the delegate

public delegate int Calculate(int a, int b);
Here you can see the we have defined the delegate with two int parameter and integer parameter as return parameter. Now any method that matches this parameter can be assigned to above delegates. To understand the functionality of delegates let’s take a following simple example.

using System;
namespace Delegates
  class Program
      public delegate int CalculateNumber(int a, int b);
      static void Main(string[] args)
          int a = 5;
          int b = 5;
          CalculateNumber addNumber = new CalculateNumber(AddNumber);
          Console.WriteLine(addNumber(5, 6));
      public static int AddNumber(int a, int b)
          return a + b;
Here in the above code you can see that I have created a object of CalculateNumber delegate and I have assigned the AddNumber static method to it. Where you can see in ‘AddNumber’ static method will just return a sum of two numbers. After that I am calling method with the help of the delegates and printing out put to the console application.

Now let’s run the application and following is the output as expected.

Deletegates in C#

That’s it. You can see the out put of delegates after adding a number. This delegates can be used in variety of scenarios. Like in web application we can use it to update one controls properties from another control’s action. Same you can also call a delegates whens some UI interaction done like button clicked.

Hope you liked it. Stay tuned for more. In next post I am going to explain about multicast delegates. Till then happy programming.

Shout it

kick it on

1 comment:

Your feedback is very important to me. Please provide your feedback via putting comments.

Support this blog-Buy me a coffee

Buy me a coffeeBuy me a coffee
Search This Blog
Subscribe to my blog


My Mvp Profile
Follow us on facebook
Blog Archive
Total Pageviews