Click here to Skip to main content
11,412,834 members (73,534 online)
Click here to Skip to main content

Understanding Delegates in C#

, 16 Sep 2005 CPOL
Rate this:
Please Sign up or sign in to vote.
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:

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

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:

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:

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

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:

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)

Share

About the Author

Arul Nayagam C
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

 
GeneralMy vote of 5 Pin
Manish Kumar Sain at 5-Apr-15 22:41
memberManish Kumar Sain5-Apr-15 22:41 
SuggestionGood article, one recommendation... Pin
Brian J Hoskins at 23-Jan-15 0:28
memberBrian J Hoskins23-Jan-15 0:28 
GeneralMy vote of 5 Pin
Member 11006604 at 14-Oct-14 20:47
memberMember 1100660414-Oct-14 20:47 
QuestionMulticast delegates must contain only methods that return void, else there is a run-time exception. [modified] Pin
sankarsan parida at 7-Oct-14 21:37
professionalsankarsan parida7-Oct-14 21:37 
QuestionUnderstanding Delegates in C# Pin
Bernard Czaiński at 24-Jun-14 2:03
memberBernard Czaiński24-Jun-14 2:03 
QuestionVery Good and Simple to Understand article, Pin
Member 10877888 at 13-Jun-14 1:37
memberMember 1087788813-Jun-14 1:37 
QuestionThanks a lot buddy! Pin
Member 10399562 at 2-Jun-14 6:25
memberMember 103995622-Jun-14 6:25 
QuestionMy vote of 5 Pin
Rahul VB at 14-May-14 23:48
professionalRahul VB14-May-14 23:48 
GeneralMy vote of 5 Pin
Purushotham Agaraharam at 5-May-14 22:47
groupPurushotham Agaraharam5-May-14 22:47 
GeneralMy vote of 5 Pin
Senthilaan at 23-Apr-14 0:44
memberSenthilaan23-Apr-14 0:44 
GeneralMy vote of 4 Pin
Animesh Datta at 11-Apr-14 0:07
memberAnimesh Datta11-Apr-14 0:07 
Generalthank you Pin
Harikrishnanvr at 19-Mar-14 19:48
memberHarikrishnanvr19-Mar-14 19:48 
thanks for the tutorials
Questiongood article Pin
nikita123deshmukh at 10-Feb-14 20:25
membernikita123deshmukh10-Feb-14 20:25 
GeneralNice basic demo Pin
srinivas_here at 10-Feb-14 9:27
membersrinivas_here10-Feb-14 9:27 
GeneralMy vote of 1 Pin
Ebram Tharwat at 17-Dec-13 3:16
memberEbram Tharwat17-Dec-13 3:16 
GeneralGood article... [modified] Pin
Atul Khanduri at 3-Dec-13 7:52
memberAtul Khanduri3-Dec-13 7:52 
QuestionCorrection to the second example Pin
John Ortiz at 12-Oct-13 18:19
memberJohn Ortiz12-Oct-13 18:19 
QuestionBut whats the Need? Pin
Upadhyay Praveen at 2-Jul-13 2:03
memberUpadhyay Praveen2-Jul-13 2:03 
AnswerRe: But whats the Need? Pin
Vishwanath Patil at 19-Jul-13 16:21
memberVishwanath Patil19-Jul-13 16:21 
AnswerRe: But whats the Need? [modified] Pin
Atul Khanduri at 3-Dec-13 7:49
memberAtul Khanduri3-Dec-13 7:49 
GeneralMy vote of 3 Pin
Jorge Altamirano at 27-Jun-13 15:58
memberJorge Altamirano27-Jun-13 15:58 
QuestionNice Pin
Member 2602122 at 7-Jun-13 4:11
memberMember 26021227-Jun-13 4:11 
AnswerRe: Nice Pin
Atul Khanduri at 3-Dec-13 11:08
memberAtul Khanduri3-Dec-13 11:08 
GeneralMy vote of 5 Pin
John Bracey at 6-Jun-13 11:07
groupJohn Bracey6-Jun-13 11:07 
GeneralGood one for startup.... Pin
deepakkarma at 13-May-13 1:14
memberdeepakkarma13-May-13 1:14 
QuestionNice Pin
KalaiselvanIT at 10-Apr-13 1:46
memberKalaiselvanIT10-Apr-13 1:46 
AnswerRe: Nice Pin
Atul Khanduri at 3-Dec-13 11:10
memberAtul Khanduri3-Dec-13 11:10 
GeneralMy vote of 3 Pin
shantanu4coding at 5-Apr-13 2:02
membershantanu4coding5-Apr-13 2:02 
SuggestionBasics Of Delegates Pin
rajeev tapadar at 25-Mar-13 7:20
memberrajeev tapadar25-Mar-13 7:20 
GeneralRe: Basics Of Delegates Pin
Atul Khanduri at 3-Dec-13 7:51
memberAtul Khanduri3-Dec-13 7:51 
GeneralMy vote of 5 Pin
symonsarwar at 21-Feb-13 6:55
membersymonsarwar21-Feb-13 6:55 
GeneralMy vote of 4 Pin
DileepMada at 6-Feb-13 21:20
memberDileepMada6-Feb-13 21:20 
QuestionMulticast Delegate Pin
Ranjan Kumar Yadav at 25-Jan-13 8:03
groupRanjan Kumar Yadav25-Jan-13 8:03 
AnswerRe: Multicast Delegate Pin
Atul Khanduri at 3-Dec-13 11:40
memberAtul Khanduri3-Dec-13 11:40 
GeneralMy vote of 5 Pin
PraveenKumarReddyChinta at 7-Jan-13 23:25
memberPraveenKumarReddyChinta7-Jan-13 23:25 
QuestionMulticast delegates must contain only methods that return void, else there is a run-time exception. Pin
Wisen Technologies at 3-Jan-13 22:03
groupWisen Technologies3-Jan-13 22:03 
GeneralMy vote of 4 Pin
Adarsh Chaurasia at 2-Dec-12 20:24
memberAdarsh Chaurasia2-Dec-12 20:24 
QuestionThanks Pin
umang_soni01 at 26-Nov-12 23:56
memberumang_soni0126-Nov-12 23:56 
AnswerRe: Thanks Pin
Atul Khanduri at 3-Dec-13 11:08
memberAtul Khanduri3-Dec-13 11:08 
GeneralMy vote of 5 Pin
VikZ91 at 7-Nov-12 16:43
memberVikZ917-Nov-12 16:43 
GeneralMy vote of 3 Pin
kiransolkar at 1-Oct-12 0:48
memberkiransolkar1-Oct-12 0:48 
GeneralMy vote of 3 Pin
kiransolkar at 1-Oct-12 0:48
memberkiransolkar1-Oct-12 0:48 
GeneralMy vote of 5 Pin
Lee Venkatsamy at 13-Sep-12 12:52
memberLee Venkatsamy13-Sep-12 12:52 
GeneralMy vote of 4 Pin
elaangovan at 19-Jul-12 2:21
memberelaangovan19-Jul-12 2:21 
GeneralVery good Pin
ambiste at 15-Jul-12 8:48
memberambiste15-Jul-12 8:48 
GeneralMy vote of 5 Pin
ajayendra2707 at 14-May-12 1:13
memberajayendra270714-May-12 1:13 
GeneralUsefull Pin
MaxAli at 26-Feb-12 1:19
memberMaxAli26-Feb-12 1:19 
GeneralMy vote of 5 Pin
vishakhakhadse at 23-Feb-12 21:46
membervishakhakhadse23-Feb-12 21:46 
GeneralMy vote of 5 Pin
Amol_Joshi at 27-Jan-12 6:34
memberAmol_Joshi27-Jan-12 6:34 
GeneralMy vote of 4 Pin
Jayanti123 at 28-Dec-11 22:04
memberJayanti12328-Dec-11 22:04 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150427.1 | Last Updated 16 Sep 2005
Article Copyright 2005 by Arul Nayagam C
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid