title: C# Foreach-loop giving Null-error
body: <p>I'm writing a bit of code, and there is a part that gives me hassles.
  I'm having the following structure in my code:</p>
  
  <pre><code>foreach (Node node in nodes)
  {
      try
      {
          bool n = node.previous == null;
      }
      catch (Exception e)
          {
              StreamWriter s = new StreamWriter("error.txt");
              s.WriteLine(e.Message);
              s.WriteLine("-----------");
              s.Close();
          }
  }
  </code></pre>
  
  <p>In here Node is a custom type, the node.prev variable is also a custom type (Location). Running this gives the following error-log:</p>
  
  <pre><code>Object reference not set to an instance of an object.
  -----------
  </code></pre>
  
  <p>I'm 100% sure that node isn't null (<em>which should be made impossible by foreach</em> = Not true, sorry!). Also, as you can see in the following listing, the Node.previous is set to null at declaration:</p>
  
  <pre><code>public class Node
  {
      public Location previous = null;
      public Location location;
      public int distance;
      ...
      ...
  }
  </code></pre>
  
  <p>I have no idea how I can fix these exeptions occuring, and  I'm kind of at the end of having any ideas on how to solve this. Can anybody help me with this?</p>
  
  <p>Note that these are all not the final code, but I sifted the parts that didn't matter!</p>
  
  <p>Thanks in advance,
  Delpee</p>
  
  <p><strong>EDIT: Ricovox helped me to the solution with <a href="https://stackoverflow.com/a/13939917/1764970">this answer</a>, thanks a lot!</strong></p>