Can anyone please tell me why does the first of the following statements throws a compilation error and the second one does not?
NewDatabase.AddInParameter(NewCommand, "@SomeString", DbType.String, SomeString ?? DBNull.Value); // <-- Throws compilation error!
NewDatabase.AddInParameter(NewCommand, "@SomeString", DbType.String, (object)(SomeString) ?? DBNull.Value); // <-- Compiles!
I tried other nullable types such as byte? and got the same result. Can anyone please tell me why do I need to cast to object first?
You need to tell the compiler what type to use. The result type of the null coalescing operator has to be the same as one of the operand types (or the underlying type of the first operand, if it's a nullable value type, in some cases). It doesn't try to find a "most specific type which both operands can be converted to" or anything like that.
For the details of how the language is defined when it comes to the null coalescing operator, see the C# 4 language specification, section 7.13:
The type of the expression
a ?? bdepends on which implicit conversions are available on the operands. In order of preference, the type ofa ?? bisA0,A, orB, whereAis the type ofa(provided that a has a type),Bis the type ofb(provided thatbhas a type), andA0is the underlying type ofAifAis a nullable type, orAotherwise.
The first example fails because SomeString and DBValue.Null are not implicitly interchangable types.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With