Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null-Coallescing Operator - Why Casting?

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?

like image 373
B.M Avatar asked Nov 27 '22 18:11

B.M


2 Answers

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 ?? b depends on which implicit conversions are available on the operands. In order of preference, the type of a ?? b is A0, A, or B, where A is the type of a (provided that a has a type), B is the type of b (provided that b has a type), and A0 is the underlying type of A if A is a nullable type, or A otherwise.

like image 68
Jon Skeet Avatar answered Dec 10 '22 06:12

Jon Skeet


The first example fails because SomeString and DBValue.Null are not implicitly interchangable types.

like image 30
user7116 Avatar answered Dec 10 '22 05:12

user7116