Why is this code invalid in C#?
- by mmattax
The following code will not compile:
string foo = "bar";
Object o = foo == null ? DBNull.Value : foo;
I get: Error 1 Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DBNull' and 'string'
To fix this, I must do something like this:
string foo = "bar";
Object o = foo == null ? DBNull.Value : (Object)foo;
This cast seems pointless as this is certainly legal:
string foo = "bar";
Object o = foo == null ? "gork" : foo;
It seems to me that when the ternary branches are of different types, the compiler will not autobox the values to the type object...but when they are of the same type then the autoboxing is automatic.
In my mind the first statement should be legal...
Can anyone describe why the compiler does not allow this and why the designers of C# chose to do this? I believe this is legal in Java...Though I have not verified this.
Thanks.
EDIT: I am asking for an understanding of why Java and C# handle this differently, what is going on underneath the scenes in C# that make this invalid. I know how to use ternary, and am not looking for a "better way" to code the examples. I understand the rules of ternary in C#, but I want to know WHY...
EDIT (Jon Skeet): Removed "autoboxing" tag as no boxing is involved in this question.