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

Advertisements

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 )

Google+ photo

You are commenting using your Google+ 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: