Is there a difference between private const and private readonly variables in C#?

后端 未结 9 1088
鱼传尺愫
鱼传尺愫 2020-12-29 03:04

Is there a difference between having a private const variable or a private static readonly variable in C# (other than having to assign the co

9条回答
  •  清歌不尽
    2020-12-29 03:26

    Readonly fields can be initialized either at the declaration or in a constructor of a class. Therefore readonly fields can have different values depending on the constructor used.

    A readonly member can also be used for runtime constants as in the following example:

    public static readonly uint currentTicks = (uint)DateTime.Now.Ticks;
    

    Readonly fields are not implicitly static, and therefore the static keyword can (must) be applied to a readonly field explicitly if required. This is not allowed for const fields, which are implicitly static.

    Readonly members can hold complex objects by using the new keyword at initialization.

提交回复
热议问题