Click here to Skip to main content
Click here to Skip to main content

Understanding Delegates in C#

By , 15 Sep 2005
 

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)

About the Author

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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralGood one for startup....memberdeepakkarma13 May '13 - 0:14 
Good one for startup....
Deepak Karma(D.K)
Web Developer

QuestionNicememberKalaiselvanIT10 Apr '13 - 0:46 
Thumbs Up | :thumbsup:
GeneralMy vote of 3membershantanu4coding5 Apr '13 - 1:02 
Good One
SuggestionBasics Of Delegatesmemberrajeev tapadar25 Mar '13 - 6:20 
Refer this Video http://www.youtube.com/watch?v=-OJ9rLmbpWU[^]. Good explanation
GeneralMy vote of 5membersymonsarwar21 Feb '13 - 5:55 
good for start up with delegate
GeneralMy vote of 4memberDileepMada6 Feb '13 - 20:20 
Good Article
QuestionMulticast DelegategroupRanjan Kumar Yadav25 Jan '13 - 7:03 
Why Multicast Delegate return type is Void?
GeneralMy vote of 5memberPraveenKumarReddyChinta7 Jan '13 - 22:25 
Simple and clean article to start delegate learning
QuestionMulticast delegates must contain only methods that return void, else there is a run-time exception.groupWisen Technologies3 Jan '13 - 21:03 
Multicast delegates must contain only methods that return void, else there is a run-time exception.
 
The above statement is not exactly correct.
 
It is not mandatory to have methods that return void. You can have methods with return values.
 
If the delegate returns a value, then the value returned by the last method in the method calling list becomes the return value of the entire delegate invocation.
 
.Net Training
GeneralMy vote of 4memberAdarsh Chaurasia2 Dec '12 - 19:24 
It is simple for beginners.

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

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