What is the difference between const and readonly in C#?

前端 未结 30 2857
挽巷
挽巷 2020-11-22 05:05

What is the difference between const and readonly in C#?

When would you use one over the other?

30条回答
  •  再見小時候
    2020-11-22 05:42

    Another gotcha.

    Since const really only works with basic data types, if you want to work with a class, you may feel "forced" to use ReadOnly. However, beware of the trap! ReadOnly means that you can not replace the object with another object (you can't make it refer to another object). But any process that has a reference to the object is free to modify the values inside the object!

    So don't be confused into thinking that ReadOnly implies a user can't change things. There is no simple syntax in C# to prevent an instantiation of a class from having its internal values changed (as far as I know).

提交回复
热议问题