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

后端 未结 9 1075
鱼传尺愫
鱼传尺愫 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:25

    There is notable difference between const and readonly fields in C#.Net

    const is by default static and needs to be initialized with constant value, which can not be modified later on. Change of value is not allowed in constructors, too. 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 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. So, it gives advantage when used as instance class member. Two different instantiation may have different value of readonly field. For ex -

    class A
    {
        public readonly int Id;
    
        public A(int i)
        {
            Id = i;
        }
    }
    

    Then readonly field can be initialised with instant specific values, as follows:

    A objOne = new A(5);
    A objTwo = new A(10);
    

    Here, instance objOne will have value of readonly field as 5 and objTwo has 10. Which is not possible using const.

提交回复
热议问题