Rostyslav Fedyk
Rostyslav Fedyk

Reputation: 307

Using ?? operator with different types

I Have something like this in my code when composing SQL query

if (query.BlackWhiteListFieldMatchProxy[i].MatchValue2Or != null)
                parameters.Add($"@matchValue2Or{i}", query.BlackWhiteListFieldMatchProxy[i].MatchValue2Or);
            else
                parameters.Add($"@matchValue2Or{i}", DBNull.Value);

And I want It to be like

parameters.Add($"@matchValue2Or{i}", query.BlackWhiteListFieldMatchProxy[i].MatchValue2Or ?? DBNull.Value);

Compiler doesn't let me run this. I tried casting to object DBNull.Value - I ended up with runtime exception, the same thing when casting other one

Upvotes: 1

Views: 89

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 249796

The types must be the same, but they can be object so you can cast the value to object

parameters.Add($"@matchValue2Or{i}", query.BlackWhiteListFieldMatchProxy[i].MatchValue2Or as object ?? DBNull.Value);

Upvotes: 1

Related Questions