'Static readonly' vs. 'const'

前端 未结 18 2912
旧巷少年郎
旧巷少年郎 2020-11-22 04:07

I\'ve read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things

18条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-22 05:09

    There is a minor difference between const and static readonly fields in C#.Net

    const must be initialized with value at compile time.

    const is by default static and needs to be initialized with constant value, which can not be modified later on. It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.

    public const DateTime dt = DateTime.Today;  //throws compilation error
    public const string Name = string.Empty;    //throws compilation error
    public static readonly string Name = string.Empty; //No error, legal
    

    readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor once. So there is a possibility to change value of readonly field once (does not matter, if it is static or not), which is not possible with const.

提交回复
热议问题