Home > DeveloperSection > Blogs > Delegate

Delegate


C# C# 
Ratings:
0 Comment(s)
 1835  View(s)
Rate this:

Delegate

Delegates in C# allow us to dynamically change the reference to the methods in a class. A delegate is a reference type variable, which holds the reference to a method.  This function can be changed at runtime as desired.  This means that you can decide the execution of a method a runtime, based on the requirements of your application.

Declaring Delegates

public delegate int MyDelegate(int num1, int num2);

    // this declaration defines a delegate named MyDelegate,

    //which will encapsulate any method that takes two integer parameters and      returnsinteger value.

Instantiating Delegates

MyDelegate objMyDelegate = new MyDelegate(SampleDelegate.Sum);

Example: -       

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Delegates

{

public delegate int MyDelegate(int num1, int num2);

// this declaration defines a delegate named MyDelegate,

//which will encapsulate any method that takes two integer parameters and returnsinteger value.

class SampleDelegate

{

publicstatic int Sum(int var1, int var2)

{

return var1 + var2;

}

publicstatic void Subtract(int var1,int var2)

{

Console.WriteLine(var1 - var2);

}

}

class Program

{

staticvoid Main(string[] args)

{

//Creating the Delegate Instance

MyDelegate objMyDelegate = new MyDelegate(SampleDelegate.Sum);

Console.WriteLine("Sum of two Numbers is : "+objMyDelegate(2, 3)); //use a delegate for processing

MyDelegate objMyDelegate1 = new MyDelegate(SampleDelegate.Subtract);

// It will generate n error because function definition is not mathing

// with the delegate its has been calling

}

}

}

Output

Sum of two Numbers is: 5


Don't want to miss updates? Please click the below button!

Follow MindStick