#339 – Readonly Fields vs. Read-Only Properties
June 6, 2011 Leave a comment
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); } }