#339 – Readonly Fields vs. Read-Only Properties

A read-only property in a class is similar to a readonly field.  Both expose a value that users of the class can read, but not write.

A readonly field is defined using the readonly modifier.  A read-only property is defined by including a get accessor for the property, but not a set accessor.

A readonly field can have only a single value, set either at the time that the field is declared, or in a constructor.  A read-only property returns a value that may be different each time the property is read.

Example of a readonly field:

        // Readonly field, initialized in constructor
        public readonly string OriginalName;

        public Dog(string name)
        {
            Name = name;

            // Set readonly field once, in the constructor
            OriginalName = name;
        }

Example of a read-only property:

        public string FormalName
        {
            get
            {
                return string.Format("Sir {0}", Name);
            }
        }

#246 – Implementing a Read-Only Property

You implement a read-only property in a class by implementing the get accessor, but not the set accessor.  This will allow client code to read the property’s value, but not write to it directly.

Below is an example of a read-only property for the Dog class.  The WhenLastBarked property returns a DateTime value indicating the last time that the Dog barked–i.e. the last time that someone called the Bark method.

    // Backing variable storing date/time last barked
    private DateTime lastBarked;

    // Public property, allows reading lastBarked
    public DateTime WhenLastBarked
    {
        get
        {
            return lastBarked;
        }
    }

    // Bark method also sets lastBarked
    public void Bark()
    {
        Console.WriteLine("{0}: Woof!", Name);
        lastBarked = DateTime.Now;
    }

We now have a property in the Dog class that we can read from, but not write to.

    kirby.Bark();
    DateTime whenHeBarked = kirby.WhenLastBarked;