#337 – Declaring and Using Static readonly Fields

A readonly field in a class can be a static or an instance field.

A static readonly field is a field that has a single read-only value, regardless of the number of instances of the parent class.  Client classes can read from, but not write to, the field.  The field is initialized either as part of the declaration or within a static constructor.

        // Static readonly field, initialized at declaration time
        public static readonly string TheDogMotto = "Man's Best Friend";

        // Static readonly field, initialized in a constructor
        public static readonly uint NumberOfLegs;

        static Dog()
            NumberOfLegs = 4;

Other code can read these fields.

            string motto = Dog.TheDogMotto;
            uint numLegs = Dog.NumberOfLegs;

#258 – Initializing a Static Variable as Part of Its Declaration

You can initialize a static variable at the time that it is declared.

        private static string LastDogToBark = "NOBODY";

The initialization of the field happens at runtime and is guaranteed to happen prior to the first time that the field is referenced or used.

#257 – Private Static Fields

A class can define not just public static fields, but also private static fields.  Because the field is static, there is just one copy of the associated data stored–regardless of the number of instances of the class.  And because the field is private, it’s not visible to code outside of the class.

In the example below, the Dog class defines two private static variables, used for tracking the last dog who barked.

        // Static fields
        private static DateTime LastTimeSomebodyBarked;
        private static string LastDogToBark;

        // Instance method
        public void Bark()
            Console.WriteLine("{0}: Woof", Name);
            LastTimeSomebodyBarked = DateTime.Now;
            LastDogToBark = Name;

#255 – Static Fields vs. Instance Fields

When you declare a field in a class using the syntax below, you get an instance field, meaning that you’ll get one copy of the field’s data for each instance of the class that is created.  The field’s data is stored in the object (an instance of the class).

    public class Dog
        public string Name;    // Instance field

You can also define static fields in a class.  A static field is a variable where we can store a piece of data for the entire class, rather than a piece of data for each instance of the class.

You declare a static field using the static keyword.

    public class Dog
        // Static field
        public static string Motto = "Man's best friend";

With static fields, we always have exactly one copy of the field, no matter how many instances of the class we create.