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

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

    Just to add, readonly for reference types only makes the reference read only not the values. For example:

    public class Const_V_Readonly
    {
      public const int I_CONST_VALUE = 2;
      public readonly char[] I_RO_VALUE = new Char[]{'a', 'b', 'c'};
    
      public UpdateReadonly()
      {
         I_RO_VALUE[0] = 'V'; //perfectly legal and will update the value
         I_RO_VALUE = new char[]{'V'}; //will cause compiler error
      }
    }
    

提交回复
热议问题