Difference between const and readonly

Both const and readonly variables are used for the same purpose that not allowing the change of the variable once intialized.
    A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants.
    So if you want to change the const value,you must modified in code and rebiuld again.
    const are static by default,where with readonly, you must define it as static (if you want it to be).
    public class Const_Vs_Readonly
    {
      public const int constNumber = 2;
      public readonly int readonlyMinNumber = 2;
      public readonly int readonlyMaxNumber;
      public Const_Vs_Readonly()
      {
       readonlyMaxNumber = 1000;
      }
    }

Home

No comments:

Post a Comment