Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Apart from the apparent difference of </p> <ul> <li>having to declare the value at the time of a definition for a <code>const</code> VS <code>readonly</code> values can be computed dynamically but need to be assigned before the constructor exits.. after that it is frozen.</li> <li>'const's are implicitly <code>static</code>. You use a <code>ClassName.ConstantName</code> notation to access them.</li> </ul> <p>There is a subtle difference. Consider a class defined in <code>AssemblyA</code>.</p> <pre><code>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; } } </code></pre> <p><code>AssemblyB</code> references <code>AssemblyA</code> and uses these values in code. When this is compiled, </p> <ul> <li>in the case of the <code>const</code> value, it is like a find-replace, the value 2 is 'baked into' the <code>AssemblyB</code>'s IL. This means that if tomorrow I'll update <code>I_CONST_VALUE</code> to 20 in the future. <em><code>AssemblyB</code> would still have 2 till I recompile it</em>.</li> <li>in the case of the <code>readonly</code> value, it is like a <code>ref</code> to a memory location. The value is not baked into <code>AssemblyB</code>'s IL. This means that if the memory location is updated, <code>AssemblyB</code> gets the new value without recompilation. So if <code>I_RO_VALUE</code> is updated to 30, you only need to build <code>AssemblyA</code>. All clients do not need to be recompiled.</li> </ul> <p>So if you are confident that the value of the constant won't change use a <code>const</code>. </p> <pre><code>public const int CM_IN_A_METER = 100; </code></pre> <p>But if you have a constant that may change (e.g. w.r.t. precision).. or when in doubt, use a <code>readonly</code>. </p> <pre><code>public readonly float PI = 3.14; </code></pre> <p><em>Update: Aku needs to get a mention coz he pointed this out first. Also I need to plug where I learned this.. <a href="http://rads.stackoverflow.com/amzn/click/0321245660" rel="noreferrer">Effective C# - Bill Wagner</a></em></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload