Labels

Thursday, May 31, 2007

Checking for null values is tricky

Checking for null values is tricky. Testing a variable only against null could give quite misleading results.

 

There is difference between a method not returning any value and a method returning a value where the content of the value is null. Consider following code snippet.

 

using (SqlConnection conn = new SqlConnection(connString))
{
                SqlCommand cmd = new SqlCommand("SELECT Color FROM Production.Product WHERE ProductID = 1", conn);
                conn.Open();
                object result = cmd.ExecuteScalar().ToString();

 

                if (result == null)
                    MessageBox.Show("Product not found");
                else if (result == System.DBNull.Value)
                    MessageBox.Show("Product found but Color is null");
                else MessageBox.Show(result.ToString());

}

In first case, the ExecuteScalar method doesn't return any result which means that the product is not found. In second case, the product is found but the value of color is stored as null. And in third case, the product is found and the value of it's color is non-null.

 

 

Thanks & Regards,

Arun Manglick

SMTS || Microsoft Technology Practice || Bridgestone - Tyre Link || Persistent Systems || 3023-6258

 

DISCLAIMER ========== This e-mail may contain privileged and confidential information which is the property of Persistent Systems Pvt. Ltd. It is intended only for the use of the individual or entity to which it is addressed. If you are not the intended recipient, you are not authorized to read, retain, copy, print, distribute or use this message. If you have received this communication in error, please notify the sender and delete all copies of this message. Persistent Systems Pvt. Ltd. does not accept any liability for virus infected mails.

No comments:

Post a Comment