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

前端 未结 30 2841
挽巷
挽巷 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:37

    The difference is that the value of a static readonly field is set at run time, so it can have a different value for different executions of the program. However, the value of a const field is set to a compile time constant.

    Remember: For reference types, in both cases (static and instance), the readonly modifier only prevents you from assigning a new reference to the field. It specifically does not make immutable the object pointed to by the reference.

    For details, please refer to C# Frequently Asked Questions on this topic: http://blogs.msdn.com/csharpfaq/archive/2004/12/03/274791.aspx

提交回复
热议问题