The C# code below:
int? i; i = (true ? null : 0);
gives me the error:
Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'int'
Shouldn't this be valid? What am i missing here?
double is a value type, which means it always needs to have a value. Reference types are the ones which can have null reference. So, you need to use a "magic" value for the double to indicate it's not set (0.0 is the default when youd eclare a double variable, so if that value's ok, use it or some of your own.
As you know, a value type cannot be assigned a null value. For example, int i = null will give you a compile time error. C# 2.0 introduced nullable types that allow you to assign null to value type variables.
You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.
In C# 8.0, strings are known as a nullable “string!”, and so the AllowNull annotation allows setting it to null, even though the string that we return isn't null (for example, we do a comparison check and set it to a default value if null.)
The compiler tries to evaluate the right-hand expression. null
is null
and the 0
is an int
literal, not int?
. The compiler is trying to tell you that it can't determine what type the expression should evaluate as. There's no implicit conversion between null
and int
, hence the error message.
You need to tell the compiler that the expression should evaluate as an int?
. There is an implicit conversion between int?
and int
, or between null
and int?
, so either of these should work:
int? x = true ? (int?)null : 0; int? y = true ? null : (int?)0;
You need to use the default() keyword rather than null when dealing with ternary operators.
Example:
int? i = (true ? default(int?) : 0);
Alternately, you could just cast the null:
int? i = (true ? (int?)null : 0);
Personally I stick with the default()
notation, it's just a preference, really. But you should ultimately stick to just one specific notation, IMHO.
HTH!
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