#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
                return string.Format("Sir {0}", Name);

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: