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

AI Evolution Explained: GenAI vs LLMs vs AI Agents vs Agentic AI vs Intelligent AI

Artificial Intelligence (AI) is one of the most exciting technologies in our world today. But the terms that come with it like GenAI, LLMs, ...

MSDEVBUILD - English Channel

MSDEVBUILD - Tamil Channel

Popular Posts