Hi,
I am trying to learn on how to use delegates efficiently in C# and I was just wondering if anyone can guide me through... The following is a sample implementation using delegates... All I am doing is just passing a value through a delegate from one class to another... Please tell me if this is the right way to implement... And also your suggestions...
Also, please note that I have de-registered the delegate in :
void FrmSample_FormClosing(object sender, FormClosingEventArgs e)
{
sampleObj.AssignValue -= new Sample.AssignValueDelegate(AssignValue);
}
Is this de-registration necessary?
The following is the code that I have written..
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 provide your feedback on whether this is right...
Thanks, Ram