Supporting initialization using the ISupportInitialize

This post doesn’t really explain anything too exciting, it’s more a reminder to myself on the existence and possible use of this interface

Admittedly the ISupportInitialize interface tends to be thought of, almost exclusively at times, as an interface used by UI controls/components. In that if you look at the code in the designer.cs file you may find controls which support ISupportInitialize, for example

((System.ComponentModel.ISupportInitialize)(this.grid)).BeginInit();

this.grid.Name = "grid";
this.grid.Size = new System.Drawing.Size(102, 80);
this.grid.TabIndex = 5;

((System.ComponentModel.ISupportInitialize)(this.grid)).EndInitInit();

But this interface is, ofcourse, not limited to controls/components. It’s defined for “simple, transacted notification for batch initialization” so why not reuse it for initialization of other code if need be.

In situations where your code might be getting setup/initialized and you maybe not wanting events to fire or the likes during the initialization phase, why not just implement the ISupportInitialize interface and use the BeginInit, EndInit pattern.

How about creating a simple helper class to automatically call a classes BeginInit and EndInit methods if it supports the ISupportInitialize

public class SupportInitialization : IDisposable
{
   private ISupportInitialize initSupported;
   public SupportInitialization(object o)
   {
      initSupported = o as ISupportInitialize;
      if (initSupported != null)
         initSupported.BeginInit();
   }

   public void Dispose()
   {
      if (initSupported != null)
         initSupported.EndInit();
   }
}