SoFunction
Updated on 2025-03-06

C# uses delegate to implement a method of passing data between two forms

This article describes the method of C# using delegate to pass data between two forms. Share it for your reference. The specific analysis is as follows:

Delegate [agent, delegate] is a very important concept in C#. It can be deduced to pointers in C++, and it can be continued to anonymous methods and lambda expressions backwards.

Now I will analyze the use of Delegate from the simplest and most practical example.

There are now two forms Form1 and Form2.

Two buttons Button1 (Form) and Button2 (Form2).

Form1's code:

private void button1_Click(object sender, EventArgs e)
{
  Form2 frm = new Form2();
   += new (SetProperty2);
  ();
}
private void SetProperty2()
{
  ("ok");
}

Form2 code:

public delegate void DelegateText();
public DelegateText SetProperty;
private void button2_Click(object sender, EventArgs e)
{
  SetProperty();
}

Analyzer two short codes can see some benefits of Delegate. When I wrote this function, I passed the form1 object to form2. After clicking form2, the object from1 copper drum object to call form1's public method. Such code always feels awkward, which is the so-called type insecure. It requires the method to be called, and the object to form1 needs to be passed to form2. Obviously, it is not the best solution.

Now that Delegate is available, the problem is solved. It is equivalent to new form2, I asked form2 to update the properties instead of me, so that my method does not need to be exposed, and form2 can only call this method, which achieves the so-called type safety statement. Although this is a small example, it can be seen through the process and see some of the benefits of Delegate.

I hope this article will be helpful to everyone's C# programming.