0

When is recommended to use read-only properties -- if the language allows me?

Are public read-only properties meant to replace getter methods or at least the Magic Methods like what is available as __get() in PHP for example?

What is the use of a private read-only property?

4
  • To add to @Uri Agassi's answer, the readonly property which is available in C# (and possibly languages?) is similar to Java's final which can be applied to member fields to ensure that they are set during object construction and never changed. Commented Mar 13, 2014 at 14:51
  • @gnat: How is that a duplicate? This question asks about the use of read-only properties, that one asks about immutability? Commented Mar 17, 2014 at 18:53
  • @RobertHarvey do you think it should be closed as too broad instead? Commented Mar 17, 2014 at 18:58
  • It's a bit broad, yes. Commented Mar 17, 2014 at 18:59

1 Answer 1

4

read-only properties are assigned only once - on the initialization of the instance.

It is different from getters, since getters allow the instance itself to change the value of the property. It is different from constants, since constants are assigned on the class declaration.

One use-case for read-only properties is to define immutable objects, another is in the definition of static read-only for a singleton implementation.

Other use-cases may be in container properties (like lists and dictionaries), in which it is intended that their contents might change, but the collection itself stays with the instance for all its life-cycle. This way you can be sure that they are never nullified.

These are some use-cases of the top of my head, I'm sure that there are more...

3
  • Great! I was totally wrong about them then, thanks a lot! Commented Mar 13, 2014 at 7:50
  • 1
    how about "any time a property reflects something distinct about a class whose meaning would be invalid were it changed", like a "FileReader" object's "FilePath" property. Commented Mar 13, 2014 at 15:03
  • @DougM I love your example! Commented Mar 13, 2014 at 16:37

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.