Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The member declared as readonly gives the possibility to be changed in the (static) constructor of the class, while the const member cannot be changed at runtime. </p> <p>Declaring a field as const makes it automatically static, quoting from §10.3.7:</p> <blockquote> <p>When a field, method, property, event, operator, or constructor declaration includes a static modifier, it declares a static member. In addition, a constant or type declaration implicitly declares a static member.</p> </blockquote> <p>The third is just a read-only property which happens to always return 5. </p> <p>You should never use such a property and prefer const members where possible in order to allow the compiler and/or the jitter to perform their optimizations and to help other people reading your code (that property is kind of a WTF to me). The static readonly member has to be used if it is required a constant value initialized during the program start-up (like, for example, the number of cores of a machine). </p> <p>This is a great example from the C# specs (§10.5.2.1):</p> <blockquote> <p>A static readonly field is useful when a symbolic name for a constant value is desired, but when the type of the value is not permitted in a const declaration, or when the value cannot be computed at compile-time. In the example</p> </blockquote> <pre><code>public class Color { public static readonly Color Black = new Color(0, 0, 0); public static readonly Color White = new Color(255, 255, 255); public static readonly Color Red = new Color(255, 0, 0); public static readonly Color Green = new Color(0, 255, 0); public static readonly Color Blue = new Color(0, 0, 255); private byte red, green, blue; public Color(byte r, byte g, byte b) { red = r; green = g; blue = b; } } </code></pre> <blockquote> <p>the Black, White, Red, Green, and Blue members cannot be declared as const members because their values cannot be computed at compile-time. However, declaring them static readonly instead has much the same effect. </p> </blockquote> <p>And yet another difference (§10.5.2.2):</p> <blockquote> <p>Constants and readonly fields have different binary versioning semantics. When an expression references a constant, the value of the constant is obtained at compile-time, but when an expression references a readonly field, the value of the field is not obtained until run-time.</p> </blockquote> <p>So, summing it up, they are very different even if at a first glance they might look similar and you should use the one which best suits your intent.</p>
 

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