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

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

    Here's another link demonstrating how const isn't version safe, or relevant for reference types.

    Summary:

    • The value of your const property is set at compile time and can't change at runtime
    • Const can't be marked as static - the keyword denotes they are static, unlike readonly fields which can.
    • Const can't be anything except value (primitive) types
    • The readonly keyword marks the field as unchangeable. However the property can be changed inside the constructor of the class
    • The readonly only keyword can also be combined with static to make it act in the same way as a const (atleast on the surface). There is a marked difference when you look at the IL between the two
    • const fields are marked as "literal" in IL while readonly is "initonly"

提交回复
热议问题