Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The important part is not what happens IN this class, but what happens, when another class uses (and links to) it. Let me explain with another example:</p> <p>Assume you have a Assembly1.dll containing a class declaring</p> <pre><code>public static const int SOME_ERROR_CODE=0x10; public static readonly int SOME_OTHER_ERROR_CODE=0x20; </code></pre> <p>and another class consuming this e.g.</p> <pre><code>public int TryFoo() { try {foo();} catch (InvalidParameterException) {return SOME_ERROR_CODE;} catch (Exception) { return SOME_OTHER_ERROR_CODE;} return 0x00; } </code></pre> <p>You compile your class into Assembly2.dll and link it against Assembly1.dll, as expected, your method will return 0x10 on invalid parameters, 0x20 on other errors, 0x00 on success.</p> <p>Especially, if you create Assembly3.exe containing something like</p> <pre><code>int errorcode=TryFoo(); if (errorcode==SOME_ERROR_CODE) bar(); else if (errorcode==SOME_OTHER_ERROR_CODE) baz(); </code></pre> <p>It will work as expected (After being linked against Assembly1.dll and Assembly2.dll)</p> <p>Now if you get a new version of Assembly1.dll, that has</p> <pre><code>public const int SOME_ERROR_CODE=0x11; public readonly int SOME_OTHER_ERROR_CODE=0x21; </code></pre> <p>If you recompile Assembly3.exe and link the last fragment against new Assembly1.dll and unchanged Assembly2.dll, it will stop working as expected:</p> <p>bar() will NOT be called correctly: Assembly2.dll remembers the LITERAL 0x20, which is not the same literal 0x21 that Assembly3.exe reads out of Assembly1.dll</p> <p>baz() will be called correctly: Both Assembly2.dll and Assembly3.exe refer to the SYMBOL REFERENCE called SOME_OTHER_ERROR_CODE, which is in both cases resolved by the current version of Assembly1.dll, thus in both cases is 0x21.</p> <p>In Short: a <code>const</code> creates a <code>LITERAL</code>, a <code>readonly</code> creates a <code>SYMBOL REFERENCE</code>.</p> <p><code>LITERALS</code> are internal to the framework and can not be marshalled and thus used by native code. </p> <p>So </p> <pre><code>public static readonly String Empty = ""; </code></pre> <p>creates a <code>symbol reference</code> (resovled at time of first use by a call to the String cosntuctor), that can be marshalled an thus used from native, while </p> <pre><code>public static const String Empty = ""; </code></pre> <p>would create a literal, that can't.</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