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

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

    Constants

    • Constants are static by default
    • They must have a value at compilation-time (you can have e.g. 3.14 * 2, but cannot call methods)
    • Could be declared within functions
    • Are copied into every assembly that uses them (every assembly gets a local copy of values)
    • Can be used in attributes

    Readonly instance fields

    • Must have set value, by the time constructor exits
    • Are evaluated when instance is created

    Static readonly fields

    • Are evaluated when code execution hits class reference (when new instance is created or a static method is executed)
    • Must have an evaluated value by the time the static constructor is done
    • It's not recommended to put ThreadStaticAttribute on these (static constructors will be executed in one thread only and will set the value for its thread; all other threads will have this value uninitialized)

提交回复
热议问题