Why is the compiler not able to automatically convert the values in this expression properly?
var input = "Hello";
object x = string.IsNullOrEmpty(input) ? input : DBNull.Value;
//could try this too and get similar compile time error
object x2 = string.IsNullOrEmpty(input) ? 1 : input;
I understand that DBNull.Value cannot be cast to a string; However, I’m curious as to why it cannot be coalesced into an object because the result is just storing a reference. If you place (object) in front of DBNull.Value it will compile and run just fine.
You can fix it with:
I have found this excellent explanations in Eric Lippert’s blog post on Type inference woes:
The specification for the
?:operator states the following:In this case:
stringandDBNullaren’t the same type.stringdoesn’t have an implicit conversion toDBNullDBNulldoesn’t have an implicit conversion tostringSo we end up with a compile-time error.
The compiler doesn’t check what is the type that can "hold" those two types.