Implementation of delegates in C#

Posted by Ram on Stack Overflow See other posts from Stack Overflow or by Ram
Published on 2010-04-16T10:36:55Z Indexed on 2010/04/16 10:43 UTC
Read the original article Hit count: 266

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about c#

Related posts about delegates