Click here to Skip to main content
15,867,568 members
Articles / Desktop Programming / Windows Forms
Article

Understanding Delegates in C#

Rate me:
Please Sign up or sign in to vote.
4.34/5 (174 votes)
15 Sep 2005CPOL2 min read 831.8K   124   85
This article describes delegates in C#.

Introduction

Delegate is like a buzz word in C#.NET programming. In this article, I explain delegates, multicast delegates and their usage with the help of simple C# programs.

What is a Delegate?

Delegate is a type which  holds the method(s) reference in an object. It is also referred to as a type safe function pointer.

Advantages

  • Encapsulating the method's call from caller
  • Effective use of delegate improves the performance of application
  • Used to call a method asynchronously

Declaration

public delegate type_of_delegate delegate_name()

Example:

C#
public delegate int mydelegate(int delvar1,int delvar2)

Note

  • You can use delegates without parameters or with parameter list
  • You should follow the same syntax as in the method
    (If you are referring to the method with two int parameters and int return type, the delegate which you are declaring should be in the same format. This is why it is referred to as type safe function pointer.)

Sample Program using Delegate

C#
public delegate double Delegate_Prod(int a,int b);
class Class1
{
    static double fn_Prodvalues(int val1,int val2)
    {
        return val1*val2;
    }
    static void Main(string[] args)
    {
        //Creating the Delegate Instance
        Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);
        Console.Write("Please Enter Values");
        int v1 = Int32.Parse(Console.ReadLine());
        int v2 = Int32.Parse(Console.ReadLine());
        //use a delegate for processing
        double res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}

Explanation

Here I have used a small program which demonstrates the use of delegate.

The delegate "Delegate_Prod" is declared with double return type and accepts only two integer parameters.

Inside the class, the method named fn_Prodvalues is defined with double return type and two integer parameters. (The delegate and method have the same signature and parameter type.)

Inside the Main method, the delegate instance is created and the function name is passed to the delegate instance as follows:

C#
Delegate_Prod delObj = new Delegate_Prod(fn_Prodvalues);

After this, we are accepting the two values from the user and passing those values to the delegate as we do using method:

C#
delObj(v1,v2);

Here delegate object encapsulates the method functionalities and returns the result as we specified in the method.

Multicast Delegate

What is Multicast Delegate?

It is a delegate which holds the reference of more than one method.

Multicast delegates must contain only methods that return void, else there is a run-time exception.

Simple Program using Multicast Delegate

C#
delegate void Delegate_Multicast(int x, int y);
Class Class2
{
    static void Method1(int x, int y)
    {
        Console.WriteLine("You r in Method 1");
    }

    static void Method2(int x, int y)
    {
        Console.WriteLine("You r in Method 2");
    }

    public static void <place w:st="on" />Main</place />()
    {
        Delegate_Multicast func = new Delegate_Multicast(Method1);
        func += new Delegate_Multicast(Method2);
        func(1,2);             // Method1 and Method2 are called
        func -= new Delegate_Multicast(Method1);
        func(2,3);             // Only Method2 is called
    }
}

Explanation

In the above example, you can see that two methods are defined named method1 and method2 which take two integer parameters and return type as void.

In the main method, the Delegate object is created using the following statement:

C#
Delegate_Multicast func = new Delegate_Multicast(Method1);

Then the Delegate is added using the += operator and removed using the -= operator.

Conclusion

This article would help to understand delegates in C# using simple examples. If you have any query regarding this article, you can reach me at arul_tony@yahoo.com.

History

  • 16th September, 2005: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
Working as a Software Engineer in a MNC Company.Knowledge on C#.NET, ASP.NET, VB.NET ,VB & SQL Server.

Comments and Discussions

 
QuestionWhy , we need Delegates ? Pin
Ammar Shaukat24-Jul-17 20:00
professionalAmmar Shaukat24-Jul-17 20:00 
QuestionMulticast delegates can also contain methods with return type other than void. Pin
@nkit Bajpai26-Apr-17 3:22
professional@nkit Bajpai26-Apr-17 3:22 
BugMulticast Delegates can work fine, even if the return type is other than VOID Pin
Member 1308630826-Mar-17 21:17
Member 1308630826-Mar-17 21:17 
Generalcomment Pin
Member 12452061-Vishal13-Sep-16 4:42
Member 12452061-Vishal13-Sep-16 4:42 
GeneralMy vote of 5 Pin
Manish Kumar Sain5-Apr-15 21:41
Manish Kumar Sain5-Apr-15 21:41 
SuggestionGood article, one recommendation... Pin
bh_22-Jan-15 23:28
bh_22-Jan-15 23:28 
GeneralRe: Good article, one recommendation... Pin
LaMinTun28-Jul-15 21:23
LaMinTun28-Jul-15 21:23 
GeneralMy vote of 5 Pin
Member 1100660414-Oct-14 19:47
Member 1100660414-Oct-14 19:47 
QuestionMulticast delegates must contain only methods that return void, else there is a run-time exception. Pin
sankarsan parida7-Oct-14 20:37
professionalsankarsan parida7-Oct-14 20:37 
QuestionUnderstanding Delegates in C# Pin
Bernard Czaiński24-Jun-14 1:03
Bernard Czaiński24-Jun-14 1:03 
QuestionVery Good and Simple to Understand article, Pin
Member 1087788813-Jun-14 0:37
Member 1087788813-Jun-14 0:37 
QuestionThanks a lot buddy! Pin
Member 103995622-Jun-14 5:25
Member 103995622-Jun-14 5:25 
QuestionMy vote of 5 Pin
Rahul VB14-May-14 22:48
professionalRahul VB14-May-14 22:48 
GeneralMy vote of 5 Pin
Purushotham Agaraharam5-May-14 21:47
Purushotham Agaraharam5-May-14 21:47 
GeneralMy vote of 5 Pin
Senthilaan22-Apr-14 23:44
professionalSenthilaan22-Apr-14 23:44 
GeneralMy vote of 4 Pin
Animesh Datta10-Apr-14 23:07
Animesh Datta10-Apr-14 23:07 
Generalthank you Pin
Harikrishnanvr19-Mar-14 18:48
professionalHarikrishnanvr19-Mar-14 18:48 
Questiongood article Pin
nikita123deshmukh10-Feb-14 19:25
nikita123deshmukh10-Feb-14 19:25 
GeneralNice basic demo Pin
srinivas_here10-Feb-14 8:27
srinivas_here10-Feb-14 8:27 
GeneralMy vote of 1 Pin
Ebram Tharwat17-Dec-13 2:16
Ebram Tharwat17-Dec-13 2:16 
GeneralGood article... Pin
Atul Khanduri3-Dec-13 6:52
Atul Khanduri3-Dec-13 6:52 
QuestionCorrection to the second example Pin
John Ortiz12-Oct-13 17:19
John Ortiz12-Oct-13 17:19 
QuestionBut whats the Need? Pin
Upadhyay Praveen2-Jul-13 1:03
Upadhyay Praveen2-Jul-13 1:03 
AnswerRe: But whats the Need? Pin
Vishwanath Patil19-Jul-13 15:21
Vishwanath Patil19-Jul-13 15:21 
AnswerRe: But whats the Need? Pin
Atul Khanduri3-Dec-13 6:49
Atul Khanduri3-Dec-13 6:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.