This is a discussion on Delegates within the C# Programming forums, part of the Software Development category; What mean by delegates,how import or define in C# Thanks, Prasath.K...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| A delegate is a reference type that refers to a Shared method of a type or to an instance method of an object. Delegate is like a function pointer in C and C++. Delegate lets some other code call your function without needing to know where your function is actually located. Events are really a modified form of a delegate. Example Program: Code: using System;
class clsDelegate
{
public delegate int simpleDelegate (int a, int b);
public int add(int a, int b)
{
return (a+b);
}
public int mul(int a, int b)
{
return (a*b);
}
static void Main(string[] args)
{
clsDelegate clsDlg = new clsDelegate();
simpleDelegate add = new simpleDelegate(clsDlg.add);
simpleDelegate mul = new simpleDelegate(clsDlg.mul);
int addAns = add(10,12);
int mulAns = mul(10,10);
Console.WriteLine("Result by calling the add method using a delegate: {0}",addAns);
Console.WriteLine("Result by calling the mul method using a delegate: {0}",mulAns);
Console.Read();
}
} Last edited by Gopisoft : 07-19-2007 at 05:22 AM. |
| |||
| 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, Code: 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());
}
}
}
__________________ S.VinothkumaR Behind me is infinite power, Before me is Endless Possibility, Around me is Boundless Opportunity, Why should I fear! |
![]() |
| Thread Tools | |
| Display Modes | |
| |