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

前端 未结 30 2855
挽巷
挽巷 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:33

    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.

提交回复
热议问题