0

This question already has an answer here:

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?

marked as duplicate by gnat, user40980, Bart van Ingen Schenau, Mahdi, Kilian Foth Mar 18 '14 at 8:27

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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. – Dylan Watson Mar 13 '14 at 14:51
  • @gnat: How is that a duplicate? This question asks about the use of read-only properties, that one asks about immutability? – Robert Harvey Mar 17 '14 at 18:53
  • @RobertHarvey do you think it should be closed as too broad instead? – gnat Mar 17 '14 at 18:58
  • It's a bit broad, yes. – Robert Harvey Mar 17 '14 at 18:59
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...

  • Great! I was totally wrong about them then, thanks a lot! – Mahdi Mar 13 '14 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. – DougM Mar 13 '14 at 15:03
  • @DougM I love your example! – Mahdi Mar 13 '14 at 16:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.