0

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'"

3 Answers 3

4

Try:

cmd.Parameters.AddWithValue(param, (object)strings[param] ?? DBNull.Value);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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

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

2 Comments

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.
* tries it * You are right... It needs the trick above (object)DBNull.Value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.