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

#242 – Declaring and Using a Property in a Class

You can create instance data in a class by defining public fields.  You can read and write fields using a reference to an instance of the class.

A class more often exposes its instance data using properties, rather than fields.  A property looks like a field from outside the class–it allows you to read and write a value using a reference to the object.  But internally in the class, a property just wraps a private field, which is not visible from outside the class.

    public class Dog
    {
        // Private field, stores the dog's name
        private string name;

        // Public property, provides a way to access
        // the dog's name from outside the class
        public string Name
        {
            get { return name; }
            set { name = value; }
        }

    }

Using the property:

            Dog kirby = new Dog();

            kirby.Name = "Kirby";