SqlParameter with default value set to 0 doesn't work as expected

Meryovi picture Meryovi · Mar 18, 2011 · Viewed 9.8k times · Source

I was doing something like this:

SqlParameter param = new SqlParameter("@Param", 0) { SqlDbType = SqlDbType.Int };

private void TestParam(SqlParameter param) {
   string test = param.Value.ToString();  // Getting NullReferenceException here
}

But I stop getting the exception when I put it like this:

SqlParameter param = new SqlParameter("@Param", SqlDbType.Int)  { Value = 0 };

private void TestParam(SqlParameter param) {
    string test = param.Value.ToString();  // Everything OK
}

Can anyone tell me why SqlParameter assumes 0 is the same as null?

Edit: MSDN Explains this here: SqlParameter Constructor

Answer

slandau picture slandau · Mar 18, 2011

Use caution when you use this overload of the SqlParameter constructor to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero, as the following C# example demonstrates.

Parameter = new SqlParameter("@pname", Convert.ToInt32(0));

If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameter (string, SqlDbType) constructor overload.

Thanks Msdn :)