Implementing delegates in C #

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

+3
source share
3 answers

, , . sampleObj Form. # , :

sampleObj.AssignValue = Sample.AssignValueDelegate( , AssignValue);

Delegate.Target, AssignValue Delegate.Method.

, , sampleObj , . , sampleObj, . , , , . .

() , , sampleObj . , - , , - . . , ObjectDisposed.

+6

. obj

+1

In this case, the Action delegate may be more appropriate - this is a specific delegate form that takes 1 to 3 parameters without a return value:

Using an action delegate in C #

+1
source

Source: https://habr.com/ru/post/1741425/


All Articles