#253 – Implementing a Read-Only Automatic Property

When using the automatic property syntax,C# requires that you define both a get and a set accessor.  But with the default syntax, you end up with a read/write property.

        public int Age { get; set;  }

But what if we want a read-only property, from the client code’s perspective?  Since we’re required to define the set accessor, it looks like client code would always be able to write to the property.

The solution is that we can add a private access modifier to the set accessor.

        public int Age { get; private set; }

With the set accessor private, code external to the class can read the property’s value, but not write to it.  But code within the class can still write to the property.

Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #253 – Implementing a Read-Only Automatic Property

  1. In Visual Studio, the “propg” code snippet is your friend for this.

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: