blog

Home / DeveloperSection / Blogs / Delegate

Delegate

Anonymous User3432 11-Sep-2012

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


Updated 18-Sep-2014
I am a content writter !

Leave Comment

Comments

Liked By