views:

469

answers:

3

I just read the top answer at this post:
http://stackoverflow.com/questions/374522/problem-inserting-string-or-null-into-sql-server-database

Correct me if I'm wrong, but can the ??-operator not only be used on two variables of the same type, if not I would greatly appreciate it, if anyone could solve my minor problem.

I tried to insert some code in my project similar to the one below.

Dictionary<string, string> strings = new Dictionary<string, string>()
{
    {"@param0", strParam0},
    {"@param1", strParam1},
    {"@param2", strParam2}
};
foreach (string param in strings.Keys)
{
    cmd.Parameters.AddWithValue(param, strings[param] ?? DBNull.Value);
}

But Visual Studio complains with the following message:
"Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull'"

A: 

DBNull and Null are not the same type, nor are nullable types or reference types and DBNull. You can only use ?? with values of the same type.

One can think of the ?? operator as syntactic sugar for:

(left != null) ? left : right

And the ternary operation requires both left and right to be of the same type, so therefore left and right of the ?? operator must also be of the same type.

So, unfortunately, no.. you can't do it this way, at least not without some ugly casting.

Mystere Man
+4  A: 

Try:

cmd.Parameters.AddWithValue(param, (object)strings[param] ?? DBNull.Value);
Mehrdad Afshari
A: 
    cmd.Parameters.AddWithValue(param, strings[param] == null ? DBNull.Value : strings[param]);

Only flaw is that it will do the dictionary look up twice!

Duke of Muppets
There's another flaw - it won't compile! You can't convert directly from string to DBNull, regardless of whether you use ?? or ?: for this.
LukeH
* tries it * You are right... It needs the trick above (object)DBNull.Value
Duke of Muppets