Question

I just read the top answer at this post:
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'"

Was it helpful?

Solution

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.

OTHER TIPS

Try:

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top