Search code examples
c#windows-forms-designerstatic-constructor

Do static constructors get called when using the designer?


I want to run some registration code, both at run time AND at design time. The best way, to me, appeared to be to use a static constructor, but it does not appear to be run.

public class MyComponent : Component 
{
    static string someVar = "Static constructor not yet run";

    static MyComponent() 
    {
        someVar = "Static constuctor run";
    }

    public MyComponent()
    {
        //Do some constructor things
    }
}

Is there a way to make a static constructor run at design time? If not is there an accepted pattern for doing this kind of thing?


Solution

  • Yes, static constructor will run regardless of design time or run time. A simple test can prove it.

    public class MyComponent : Component
    {
        static string someVar = "Static constructor not yet run";
    
        static MyComponent()
        {
            someVar = "Static constructor run";
            MessageBox.Show(someVar);
        }
    
        public MyComponent()
        {
            //Do some constructor things
        }
    }
    

    Now add the component in to the designer, and Build the project. You'll see message box with message Static constructor run.