title: Can't understand why SqlConnection is returning System.NullReferenceException
body: <p>This is baffling me.  I have this line of code that is causing the problem</p>
  
  <pre><code>string prodID = DBTools.getProdID(args[0]).ExecuteScalar().ToString();
  </code></pre>
  
  <p>When I run this in my program I eventually get an error.</p>
  
  <pre><code>public static SqlCommand getProdID(string server)
      {
          string sql = "SELECT Password FROM UTrainID";
          SqlCommand cmd = createCmd(server, "AACSMapping", sql);
          cmd.Connection.Open(); // this generates the System.NullReferenceException
          return cmd;
      }
  </code></pre>
  
  <p>The thing that is baffling me about this is that I have a UnitTest that tests this that works perfectly.</p>
  
  <pre><code> [TestMethod]
      public void getProdIDTest()
      {
          string ID = UTrain.DBTools.getProdID("PN1173312").ExecuteScalar().ToString();
          Assert.IsTrue(ID.Equals("XXXXXXXXX"));
      }
  </code></pre>
  
  <p>When I run this console application I've checked that the Args[] values are right i.e. it's the same value that I have in the UnitTest.  The other things that is bothersome about this is that when I try to debug it by stepping through the code it works fine!  That tells me that it's a timing problems of some type but that's beyond me.  Here is the code that creates the actual connection.</p>
  
  <pre><code>public static SqlConnection createConnection(string server, string initcat)
      {
          try
          {
              SqlConnectionStringBuilder strBuild = new SqlConnectionStringBuilder();
              strBuild.IntegratedSecurity = true;
              strBuild.InitialCatalog = initcat;
              strBuild.DataSource = server;
              SqlConnection conn = new SqlConnection(strBuild.ConnectionString);
              return conn;
          } // end try
          catch (Exception e)
          {
              writeErrorMessage(e, "Could not create connection.");
              return null;
          }
      }
  </code></pre>
  
  <p>I don't know that it makes any difference but the reason I break the code up like this is I'm connecting to a number of different databases so it makes it easier to do it like this I feel.</p>