What is the difference between const and readonly?

2018-12-31 07:40发布

What is the difference between const and readonly and do you use one over the other?

29条回答
墨雨无痕
2楼-- · 2018-12-31 07:40

I believe a const value is the same for all objects (and must be initialized with a literal expression), whereas readonly can be different for each instantiation...

查看更多
临风纵饮
3楼-- · 2018-12-31 07:41

One thing to add to what people have said above. If you have an assembly containing a readonly value (e.g. readonly MaxFooCount = 4; ), you can change the value that calling assemblies see by shipping a new version of that assembly with a different value (e.g. readonly MaxFooCount = 5;)

But with a const, it would be folded into the caller's code when the caller was compiled.

If you've reached this level of C# proficiency, you are ready for Bill Wagner's book, Effective C#: 50 Specific Ways to Improve Your C# Which answers this question in detail, (and 49 other things).

查看更多
初与友歌
4楼-- · 2018-12-31 07:41

A const has to be hard-coded, where as readonly can be set in the constructor of the class.

查看更多
姐姐魅力值爆表
5楼-- · 2018-12-31 07:44

Constant variables are declared and initialized at compile time. The value can’t be changed after wards. Read-only variables will be initialized only from the Static constructor of the class. Read only is used only when we want to assign the value at run time.

查看更多
浅入江南
6楼-- · 2018-12-31 07:45

Apart from the apparent difference of

  • having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen.
  • 'const's are implicitly static. You use a ClassName.ConstantName notation to access them.

There is a subtle difference. Consider a class defined in AssemblyA.

public class Const_V_Readonly
{
  public const int I_CONST_VALUE = 2;
  public readonly int I_RO_VALUE;
  public Const_V_Readonly()
  {
     I_RO_VALUE = 3;
  }
}

AssemblyB references AssemblyA and uses these values in code. When this is compiled,

  • in the case of the const value, it is like a find-replace, the value 2 is 'baked into' the AssemblyB's IL. This means that if tomorrow I'll update I_CONST_VALUE to 20 in the future. AssemblyB would still have 2 till I recompile it.
  • in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA. All clients do not need to be recompiled.

So if you are confident that the value of the constant won't change use a const.

public const int CM_IN_A_METER = 100;

But if you have a constant that may change (e.g. w.r.t. precision).. or when in doubt, use a readonly.

public readonly float PI = 3.14;

Update: Aku needs to get a mention coz he pointed this out first. Also I need to plug where I learned this.. Effective C# - Bill Wagner

查看更多
姐姐魅力值爆表
7楼-- · 2018-12-31 07:46

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
    }
}
查看更多
登录 后发表回答