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

前端 未结 30 2856
挽巷
挽巷 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 a small gotcha with readonly. A readonly field can be set multiple times within the constructor(s). Even if the value is set in two different chained constructors it is still allowed.

    
    public class Sample {
        private readonly string ro;
    
        public Sample() {
            ro = "set";
        }
    
        public Sample(string value) : this() {
            ro = value; // this works even though it was set in the no-arg ctor
        }
    }
    

提交回复
热议问题