Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I set a nullable int to null in a ternary if statement? [duplicate]

Tags:

c#

asp.net

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?

like image 633
Abe Miessler Avatar asked May 04 '10 16:05

Abe Miessler


People also ask

How do you make a double nullable in C#?

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.

Can Int be nullable?

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.

What is a nullable Boolean?

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.

Can strings be nullable?

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.)


2 Answers

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; 
like image 134
LukeH Avatar answered Sep 21 '22 01:09

LukeH


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!

like image 43
code4life Avatar answered Sep 21 '22 01:09

code4life