Difference between DbNull.Value and DbNull.Value.ToString()

cihadakt picture cihadakt · Nov 20, 2013 · Viewed 12k times · Source

I wanted to learn which usage is true?

if(!string.IsNullOrEmpty(parentID))
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));
else
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

OR

if(!string.IsNullOrEmpty(parentID))
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));
else
   cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString()));

Answer

Sriram Sakthivel picture Sriram Sakthivel · Nov 20, 2013
cmd.Parameters.Add(new SqlParameter("@ParentSesID", parentID));

This is passing a parentID to parameter @ParentSesID.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value));

is passing a null value to parameter.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", DBNull.Value.ToString()));

is passing equal to string.Empty, which is not allowed in numerical data types.

cmd.Parameters.Add(new SqlParameter("@ParentSesID", null);

is same as ignoring the parameter.

So when you need to pass null to SP you've to pass DBNull.Value.