Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>It seems to depend on the sequence of lines. This code works:</p> <pre><code>static private List&lt;int&gt; a = new List&lt;int&gt;() { 1 }; static private List&lt;int&gt; b = new List&lt;int&gt;() { a[0] }; </code></pre> <p>while this code does not work (it throws a <code>NullReferenceException</code>)</p> <pre><code>static private List&lt;int&gt; a = new List&lt;int&gt;() { b[0] }; static private List&lt;int&gt; b = new List&lt;int&gt;() { 1 }; </code></pre> <p>So, obviously no rules for cyclical dependency exist. It's peculiar however that the compiler does not complain...</p> <hr> <p>EDIT - What's happening "across files"? If we declare these two classes:</p> <pre><code>public class A { public static List&lt;int&gt; a = new List&lt;int&gt;() { B.b[0] }; } public class B { public static List&lt;int&gt; b = new List&lt;int&gt;() { A.a[0] }; } </code></pre> <p>and try to access them with this code:</p> <pre><code>try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message.); } try { Console.WriteLine(A.a); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); } try { Console.WriteLine(B.b); } catch (Exception e) { Console.WriteLine(e.InnerException.Message); } </code></pre> <p>we are getting this output:</p> <pre><code>The type initializer for 'A' threw an exception. Object reference not set to an instance of an object. The type initializer for 'A' threw an exception. </code></pre> <p>So the initialization of <code>B</code> causes an exception in static constructor <code>A</code> and lefts field <code>a</code> with the default value (null). Since <code>a</code> is <code>null</code>, <code>b</code> can not also be initialized properly.</p> <p>If we do not have cyclical dependencies, everything works fine.</p> <hr> <p>EDIT: Just in case you didn't read the comments, <a href="https://stackoverflow.com/users/22656/jon-skeet">Jon Skeet</a> provides a very interesting reading: <a href="http://csharpindepth.com/Articles/General/Beforefieldinit.aspx" rel="nofollow noreferrer">The differences between static constructors and type initializers</a>.</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