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

前端 未结 30 2835
挽巷
挽巷 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"
    0 讨论(0)
  • 2020-11-22 05:41

    They are both constant, but a const is available also at compile time. This means that one aspect of the difference is that you can use const variables as input to attribute constructors, but not readonly variables.

    Example:

    public static class Text {
      public const string ConstDescription = "This can be used.";
      public readonly static string ReadonlyDescription = "Cannot be used.";
    }
    
    public class Foo 
    {
      [Description(Text.ConstDescription)]
      public int BarThatBuilds {
        { get; set; }
      }
    
      [Description(Text.ReadOnlyDescription)]
      public int BarThatDoesNotBuild {
        { get; set; }
      }
    }
    
    0 讨论(0)
  • 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).

    0 讨论(0)
  • 2020-11-22 05:44

    const: Can't be changed anywhere.

    readonly: This value can only be changed in the constructor. Can't be changed in normal functions.

    0 讨论(0)
  • 2020-11-22 05:45

    I believe a const value is the same for all objects (and must be initialized with a literal expression), whereas readonly can be different for each instantiation...

    0 讨论(0)
  • 2020-11-22 05:45

    A const has to be hard-coded, where as readonly can be set in the constructor of the class.

    0 讨论(0)
提交回复
热议问题