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

前端 未结 30 2799
挽巷
挽巷 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

    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; }
      }
    }
    

提交回复
热议问题