Introduction to Delegate

In this article I have explain the delegate in C#.
  • 4449

Introduction

Delegate is a type which  holds the methods reference in an object. When we are creating delegates, we are actually creating an object that can hold a reference to a methods.

Delegate is basically known as function pointer. A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. If you have a delegate object and an appropriate set of arguments, you can invoke the delegate with the arguments.

Now lets see a simple example how can we use the Delegate in C#

Class Delegates

{

public delegate int IntroDelegate(int a,int b);
class Intro
{
    static int Show(int x,int y)
    {
        return x*y;
    }
    static void Main(string[] args)
    {
        //Delegate Instance will created
        IntroDelegate delObj = new IntroDelegate(Show);
        int v1 = 10;
        int v2 = 20;
        //use a delegate for processing
        int res = delObj(v1,v2);
        Console.WriteLine ("Result :"+res);
        Console.ReadLine();
    }
}
}

 

Explanation of the above program

  • The delegate "IntroDelegate" is declared with int type and accepts two integer parameters. Inside the class, the method named show is defined with int return type and with two integer parameters. It is essential  to declare delegate and method with a 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:  IntroDelegate delObj = new IntroDelegate(Show).

  • After this, we are taking two values and passing those values to the delegate as we do using method.
  • Now the delegate object encapsulates the method functionalities and returns the result as we specified in the method.
Further Readings 

You may also want to read these related articles :

Ask Your Question 

Got a programming related question? You may want to post your question here

Programming Answers here

© 2020 DotNetHeaven. All rights reserved.