#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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: