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

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 )

Twitter picture

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

Facebook photo

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

Connecting to %s

%d bloggers like this: