Delegates in C#

An interesting feature in C# is Delegate. Delegates are best complemented as new type of Object in C#. They are also represented as pointer to functions. Technically delegate is a reference type used to encapsulate a method with a specific signature and return type.



There are two types of delegates available in C#.

1. Single Delegate
2. Multi-cast Delegate

Here is the example of delegate as follows,



using System;
namespace testWinApp
{

// 1. Define delegate.

public delegate double UnitConversion(double from);

public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
} // 2. Define handler method.

public static double FeetToInches(double feet)
{
return feet * 12;
}

private void button4_Click(object sender, EventArgs e)
{ // 3. Create delegate instance.

UnitConversion doConversion = new UnitConversion(FeetToInches);

// 4. Use delegate just like a method.

double inch = doConversion(4);
MessageBox.Show(inch.ToString());
}
}
}

Result will be as follows,




Cheers...

...S.VinothkumaR

No comments: