I am trying to learn how to efficiently use delegates in C #, and I'm just wondering if anyone can help me ... Below is an example implementation using delegates ... All I do is just pass the value through the delegate from one class to another ... Tell me, please, is it right to implement it ... And also your suggestions ...
Also, note that I de-registered the delegate at:
void FrmSample_FormClosing(object sender, FormClosingEventArgs e)
{
sampleObj.AssignValue -= new Sample.AssignValueDelegate(AssignValue);
}
Is this de-registration required?
Below is the code I wrote.
public partial class FrmSample : Form
{
Sample sampleObj;
public FrmSample()
{
InitializeComponent();
this.Load += new EventHandler(FrmSample_Load);
this.FormClosing += new FormClosingEventHandler(FrmSample_FormClosing);
sampleObj = new Sample();
sampleObj.AssignValue = new Sample.AssignValueDelegate(AssignValue);
}
void FrmSample_FormClosing(object sender, FormClosingEventArgs e)
{
sampleObj.AssignValue -= new Sample.AssignValueDelegate(AssignValue);
}
void FrmSample_Load(object sender, EventArgs e)
{
sampleObj.LoadValue();
}
void AssignValue(string value)
{
MessageBox.Show(value);
}
}
class Sample
{
public delegate void AssignValueDelegate(string value);
public AssignValueDelegate AssignValue;
internal void LoadValue()
{
if (AssignValue != null)
{
AssignValue("This is a test message");
}
}
}
Pls give you information on whether this is correct ...
Thanks Ram
source
share