Which is better between a readonly modifier and a private setter?

前端 未结 5 858
遥遥无期
遥遥无期 2020-12-02 09:47

I\'ve been working on creating a class and suddenly a thought came to my mind of what is the difference between the two codes:

public readonly string Product         


        
5条回答
  •  醉梦人生
    2020-12-02 10:19

    The first one (using readonly) will mean that the object can't even modify its own field's value, once the object has been instantiated, and others can never modify it.

    The second one (using private set) will mean that object can modify the value of its field after it's been instantiated, but others can never modify it.

    I would use the former for something that you know will not change, and use the latter for something where the value may change, but you don't want others to change it.

提交回复
热议问题