title: Handling null values in Command.ExecuteScalar when the value is converted to a Type
body: <p>I have a function to execute a query and return a scalar value like this:</p>
  
  <pre><code>        public T GetScalarValue&lt;T&gt;(string sql)
          {
              T t;
              try {
                  SqlConnection conn = new SqlConnection("MY_SQL_SERVER_CONNECTION_STRING");
                  conn.Open();
                  SqlCommand cmd = new SqlCommand(sql, conn);
                  t = (T)cmd.ExecuteScalar();
              }
              catch (Exception ex) {
                  throw ex;
              }
              finally{
                  if(conn.State == ConnectionState.Open)
                      conn.Close();
              }
              return t;
          }
  </code></pre>
  
  <p>When I call this function with the given SQL, I'll get the result:</p>
  
  <pre><code>int result = dal.GetScalarValue&lt;int&gt;("SELECT [schema_id] FROM SYS.SCHEMAS WHERE [name] = 'dbo'")
  </code></pre>
  
  <p>Since the query returns an int value this works fine, but when I call the same for the query which returns nothing my function will fail:</p>
  
  <pre><code>int result = dal.GetScalarValue&lt;int&gt;("SELECT [schema_id] FROM SYS.SCHEMAS WHERE [name] = 'Foooo'")
  </code></pre>
  
  <p>Since cmd.ExecuteScalar() returns no result,it will give "Object reference not set to an instance of an object" exception. But I want this function to return the default value for given Type (example: for int it should return 0, decimal-  0.00,for string - an empty value, for datetime - '1900-01-01', etc.).</p>
  
  <p>If you find better solution for this please let me know.</p>
  
  <p>Thanks in advance for the help.</p>