What is a delegate?
Microsoft framework exposes callback functionality via delegates. Call back functions are used in various application like Microsoft Windows software, OPC subscriptions in Industrial Automation software's, for providing real time data for web applications, menus, file system changes, exception handling etc. Delegates can call multiple methods in order wise.
A delegate object is a wrapper around a method and an object to operate on. All Delegates types are derived from System.Multicastdelegate. Delegate supports the calling of both static and instance methods and callback method is type safe.
How to use it?
class TempretureSensor
{
// Subscribers to the tempreture sensor instance
public List<int> subscribers = new List<int>();
//Define a sensor data type
public delegate void TemperatureFeedback(int unitId, double value, string tempunit);
public void ProcessSubscribers(TemperatureFeedback fd)
{
foreach(var item in subscribers)
{
if(fd != null)
{
//if any subscribers are present, call them
// Assuming plant 1 has id as 1
if(item==1)
fd(1, 32.5, "degree centigrade");
else if(item==2)
fd(2, 20.5, "degree centigrade");
}
}
}
}
//Instance call back example
void Unit1TempretureFeedback(int unitId, double temp, string tempunit)
{
Unit1Temp.Text = temp.ToString() + " " + tempunit;
}
//Instance call back example
private void GetUnit1tempBtn_Click(object sender, EventArgs e)
{
TempretureSensor tempSensor = new TempretureSensor();
tempSensor.subscribers.Add(1);
// Here we are creating a form instance ans subscribing for feedback
//Form1 forminstance = new Form1();
TempretureSensor.TemperatureFeedback tp = null;
//the += operator is used to append the list referred and tp refers to
//the head of the linked list
tp += new TempretureSensor.TemperatureFeedback(this.Unit1TempretureFeedback);
tempSensor.ProcessSubscribers(tp);
}
static void GetTempretureForUnit1(int Id, double temp, string unit)
{
if(Id==1)
tempretures = "For unit 1 " + temp.ToString() + " " + unit + "\n";
}
static void GetTempretureForUnit2(int Id, double temp, string unit)
{
if(Id==2)
tempretures += "For unit 2 " + temp.ToString() + " " + unit;
}
/// <summary>
/// Get for all the subscribers. this example shows how delegates can be called as static instance
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AllUnitTemp_Click(object sender, EventArgs e)
{
TempretureSensor globalTempSensor = new TempretureSensor();
TempretureSensor.TemperatureFeedback tfb = null;
// Process the items and gives feedback to a static string
globalTempSensor.subscribers.Add(1);
tfb += new TempretureSensor.TemperatureFeedback(Form1.GetTempretureForUnit1);
globalTempSensor.subscribers.Add(2);
tfb += new TempretureSensor.TemperatureFeedback(Form1.GetTempretureForUnit2);
globalTempSensor.ProcessSubscribers(tfb);
MessageBox.Show(tempretures);
}
Explaining Delegate
Each delegate declared has four methods as follows:
Delegate has a constructor that takes two parameters, object reference and an integer referring to the callback method.
System.Multicastdelegate is derived from System.Delegate and System.Delegate is derived from System.Object. Use of += on delegates leads to chain of delegates which is internally translated to Delegates' Combine method by the compiler. Similarly -= on delegates is translated to Remove method. Thus providing support for delegate chains.
class Standard1
{
public int Passpercentage()
{
return 70;
}
}
class Standard2
{
public int Passpercentage()
{
return 80;
}
}
namespace DelegateChain
{
public partial class Form1 : Form
{
delegate int GetClassResult();
public Form1()
{
InitializeComponent();
}
private void Btnresultdata_Click(object sender, EventArgs e)
{
GetClassResult results = null;
results += new GetClassResult(new Standard1().Passpercentage);
results += new GetClassResult(new Standard2().Passpercentage);
Delegate[] delegatearray = results.GetInvocationList();
foreach(GetClassResult result in delegatearray )
{
listBox1.Items.Add(result());
}
}
}
}
Dynamically use of Delegates
System.Delegate offers methods to create and invoke at run-time using methods:
{
public delegate void NameAndClass(string name, string cls);
public delegate void NameOnly(string name);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Studentname(string name)
{
txtName1.Text = name;
}
public void StudentDetails(string name, string cls)
{
txtName2.Text = name;
txtClass.Text = cls;
}
private void BtnInvoke_Click(object sender, EventArgs e)
{
Delegate del;
// Create deleagte based on the type chosen
Type delegatetype = radiobtndel1.Checked ? typeof(NameOnly) : typeof(NameAndClass);
string methodName = radiobtndel1.Checked ? "Studentname": "StudentDetails";
// Creates delegate in the run time
del = Delegate.CreateDelegate(delegatetype, this, methodName);
//Invoke the deleagte
// Arguments to the call back functions
int argumentLength = radiobtndel1.Checked ? 1 : 2;
object[] arguments = new object[argumentLength];
if(del.GetType() == typeof(NameOnly))
{
arguments[0] = "Harsit";
}
else
{
arguments[0] = "Harsit";
arguments[1] = "Class 2";
}
del.DynamicInvoke(arguments);
}
}
}
Microsoft framework exposes callback functionality via delegates. Call back functions are used in various application like Microsoft Windows software, OPC subscriptions in Industrial Automation software's, for providing real time data for web applications, menus, file system changes, exception handling etc. Delegates can call multiple methods in order wise.
A delegate object is a wrapper around a method and an object to operate on. All Delegates types are derived from System.Multicastdelegate. Delegate supports the calling of both static and instance methods and callback method is type safe.
How to use it?
class TempretureSensor
{
// Subscribers to the tempreture sensor instance
public List<int> subscribers = new List<int>();
//Define a sensor data type
public delegate void TemperatureFeedback(int unitId, double value, string tempunit);
public void ProcessSubscribers(TemperatureFeedback fd)
{
foreach(var item in subscribers)
{
if(fd != null)
{
//if any subscribers are present, call them
// Assuming plant 1 has id as 1
if(item==1)
fd(1, 32.5, "degree centigrade");
else if(item==2)
fd(2, 20.5, "degree centigrade");
}
}
}
}
//Instance call back example
void Unit1TempretureFeedback(int unitId, double temp, string tempunit)
{
Unit1Temp.Text = temp.ToString() + " " + tempunit;
}
//Instance call back example
private void GetUnit1tempBtn_Click(object sender, EventArgs e)
{
TempretureSensor tempSensor = new TempretureSensor();
tempSensor.subscribers.Add(1);
// Here we are creating a form instance ans subscribing for feedback
//Form1 forminstance = new Form1();
TempretureSensor.TemperatureFeedback tp = null;
//the += operator is used to append the list referred and tp refers to
//the head of the linked list
tp += new TempretureSensor.TemperatureFeedback(this.Unit1TempretureFeedback);
tempSensor.ProcessSubscribers(tp);
}
static void GetTempretureForUnit1(int Id, double temp, string unit)
{
if(Id==1)
tempretures = "For unit 1 " + temp.ToString() + " " + unit + "\n";
}
static void GetTempretureForUnit2(int Id, double temp, string unit)
{
if(Id==2)
tempretures += "For unit 2 " + temp.ToString() + " " + unit;
}
/// <summary>
/// Get for all the subscribers. this example shows how delegates can be called as static instance
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AllUnitTemp_Click(object sender, EventArgs e)
{
TempretureSensor globalTempSensor = new TempretureSensor();
TempretureSensor.TemperatureFeedback tfb = null;
// Process the items and gives feedback to a static string
globalTempSensor.subscribers.Add(1);
tfb += new TempretureSensor.TemperatureFeedback(Form1.GetTempretureForUnit1);
globalTempSensor.subscribers.Add(2);
tfb += new TempretureSensor.TemperatureFeedback(Form1.GetTempretureForUnit2);
globalTempSensor.ProcessSubscribers(tfb);
MessageBox.Show(tempretures);
}
Explaining Delegate
Each delegate declared has four methods as follows:
- Constructor
- Invoke
- Begin Invoke
- End Invoke
Delegate has a constructor that takes two parameters, object reference and an integer referring to the callback method.
System.Multicastdelegate is derived from System.Delegate and System.Delegate is derived from System.Object. Use of += on delegates leads to chain of delegates which is internally translated to Delegates' Combine method by the compiler. Similarly -= on delegates is translated to Remove method. Thus providing support for delegate chains.
class Standard1
{
public int Passpercentage()
{
return 70;
}
}
class Standard2
{
public int Passpercentage()
{
return 80;
}
}
namespace DelegateChain
{
public partial class Form1 : Form
{
delegate int GetClassResult();
public Form1()
{
InitializeComponent();
}
private void Btnresultdata_Click(object sender, EventArgs e)
{
GetClassResult results = null;
results += new GetClassResult(new Standard1().Passpercentage);
results += new GetClassResult(new Standard2().Passpercentage);
Delegate[] delegatearray = results.GetInvocationList();
foreach(GetClassResult result in delegatearray )
{
listBox1.Items.Add(result());
}
}
}
}
Dynamically use of Delegates
System.Delegate offers methods to create and invoke at run-time using methods:
- CreateDelegate
- DynamicInvoke
{
public delegate void NameAndClass(string name, string cls);
public delegate void NameOnly(string name);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Studentname(string name)
{
txtName1.Text = name;
}
public void StudentDetails(string name, string cls)
{
txtName2.Text = name;
txtClass.Text = cls;
}
private void BtnInvoke_Click(object sender, EventArgs e)
{
Delegate del;
// Create deleagte based on the type chosen
Type delegatetype = radiobtndel1.Checked ? typeof(NameOnly) : typeof(NameAndClass);
string methodName = radiobtndel1.Checked ? "Studentname": "StudentDetails";
// Creates delegate in the run time
del = Delegate.CreateDelegate(delegatetype, this, methodName);
//Invoke the deleagte
// Arguments to the call back functions
int argumentLength = radiobtndel1.Checked ? 1 : 2;
object[] arguments = new object[argumentLength];
if(del.GetType() == typeof(NameOnly))
{
arguments[0] = "Harsit";
}
else
{
arguments[0] = "Harsit";
arguments[1] = "Class 2";
}
del.DynamicInvoke(arguments);
}
}
}
Comments
Post a Comment