Role of BeginInit () and EndInit () methods in Designer

It’s red for me that those methods of the ISupportInitialize interface are used by the Designer to support optimization, ensure atomicity of initialization of controls and prevent any actions on controls during initialization. My questions:

  • How do they help the designer optimize the initialization of the controls?
  • Why to ensure atomic initialization?
  • Is there any reasonable example when to use them in code not created by the constructor?
+8
c # winforms
source share
2 answers

This has nothing to do with optimization. ISupportInitialize is the interface you need when your control is sensitive to the order in which the properties are assigned. There is no way to influence the order in which the designer assigns them; he does this in alphabetical order.

Usually you set the bool variable to true in your BeginInit() method, you check this in the properties settings and do nothing when it is set. Then your EndInit() method makes the property values ​​efficient.

You can see a good example of this in the ErrorProvider Component . Notice how it uses methods to transfer data bindings. Another good example is the PictureBox control , which uses it to delay the loading of images. TrackBar is another example, it uses it to ensure that the Value property is between the minimum and maximum. Etcetera, the source of the .NET Framework, is often a very good place to see how .NET types are used in practice.

+5
source share

By definition, the designer allows you to create controls in visual mode, the appropriate code for initializing the controls is then generated by Visual Studio.

Initialization is done in one place to avoid any null reference problem later in your code. You really expect that all controls are already created when you use their link.

You can create the initialization of your controls if, for example, you want to dynamically create your interface based on a specific constructor.

0
source share

All Articles