#254 – Implementing a Read-Only Property with a Private Set Accessor

One way to implement a read-only property is to provide only a get accessor, letting the code internal to the class write the property’s value by writing directly to a private backing variable.

        private string personalHowl;
        public string PersonalHowl
        {
            get { return personalHowl; }
        }

However, it still might be helpful for code in the class to have a set accessor, which serves as a single place to execute whatever code is required when writing the property’s value.

You can use the private access modifier to make the set accessor available only to code within the class.  The property will appear to be read-only from code outside of the class.

        private string personalHowl;
        public string PersonalHowl
        {
            get { return personalHowl; }

            private set { personalHowl = value.ToUpper(); }
        }
Advertisement

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: