Runtime Assign Method using Delegate

Writing Plug-in Methods with Delegates

A delegate variable is assigned a method dynamically. This is useful for writing plug-in methods. In this example, we have a utility method named Add,Sub that appliesa NumberOper . The NumberOper method has a delegateparameter,



///
/// delegate declaration
///
///
///
///
public delegate int NumberOperation(int fvalue, int svalue);
///
/// Button click event it will call NumberOper method
///
///
/// 
private void btnClick_Click(object sender, EventArgs e)
{
int a = Convert.ToInt16(txtfvalue.Text);
int b = Convert.ToInt16(txtsvalue.Text);
txtresult.Text = NumberOper(a, b, Add).ToString();//Dynamic we Assign Method name
}
///
/// Button click event it will call NumberOper method
///
///
/// 
private void btnSub_Click(object sender, EventArgs e)
{
int a = Convert.ToInt16(txtfvalue.Text);
int b = Convert.ToInt16(txtsvalue.Text);
txtresult.Text = NumberOper(a, b, Sub).ToString(); //Dynamic we Assign Method name
}
///
/// Main Method with delegate Parameter
///
/// first value
/// second value
/// Dynamic Delegate
/// call method add or sub and return result
public int NumberOper(int a, int b, NumberOperation AT)
{
return AT(a, b);
}
///
/// Add two numbers Methos
///
/// first Value
/// Second value
/// Result

public int Add(int a, int b)
{
return a + b;
}
///
/// Sub two number
///
/// first value
/// Second value
/// int value

public int Sub(int a, int b)
{
return a - b;
}

0 Comments

Featured Post

Understanding about Azure Region, Geographies, Availability Zones and Region Pairs

Introduction Microsoft Azure services are available in 53 regions around the world, with plans announced for 7 additional regions and 140+ a...

Subscribe to the FREE Weekly Newsletter to receive all the latest Microsoft Azure, AI, Xamarin

Popular Posts