#314 – Access Modifiers Are Not Allowed on Static Constructors

Because you can’t call a static constructor directly, you can’t include an access modifier (e.g. public, private) when defining a static constructor.  Static constructors are defined without access modifiers.

        static Dog()
        {
            Motto = "We serve humans.  And lick ourselves.";
        }

The compiler will generate an error if you try to include an access modifier.

Advertisement

#295 – When Is a Static Constructor Called?

You cannot dictate when a static constructor will be called and you can’t call it directly.

More specifically, a static constructor will be called just before you do one of the following:

  • Create an instance of the type
  • Access any static data in the type
  • Start executing Main method (in the same class as the static constructor)

If we have the following implementation in the Dog class:

        public Dog(string name)
        {
            Console.WriteLine("Dog constructor");
            Name = name;
        }

        public static string Motto = "Wag all the time";

        static Dog()
        {
            Console.WriteLine("Static Dog constructor");
        }

And we create a Dog instance:

 Console.WriteLine("Here 1");
 Dog d1 = new Dog("Kirby");
 Console.WriteLine("Here 2");

We get this output (static constructor called before object instantiation):

Or if we access static data:

            Console.WriteLine("Here 1");
            string s = Dog.Motto;
            Console.WriteLine("Here 2");

The output is (static constructor called before accessing static data):