#292 – A Static Constructor Initializes Static Data

In the same way that you can define instance constructors to initialize instance data in a class, you can define a static constructor to initialize any static data in the class.

A static constructor is defined using the static keyword and the name of the class.  The constructor takes no arguments and you can only define one static constructor.  You do not declare a static constructor as either public or private.

        public static string Motto { get; set; }
        public static int NumDogs { get; private set; }

        static Dog()
            Motto = "We're like wolves.  Only friendlier.";
            NumDogs = 0;

You cannot dictate when a static constructor will be called and you can’t call it directly.  The compiler guarantees that it will be called automatically before you create any instances of your class or access any static data.