Nullable Convert ? : operand problem

  • Thread starter Thread starter mihkeltt
  • Start date Start date
M

mihkeltt

Just one question, why wouldn't the following lines compile:

decimal? decVar = 5;
int? intVar = decVar == null ? null :
Convert.ToInt32(decVar.GetValueOrDefault());

The compiler shows the following message: "There is no implicit conversion
between 'null' and 'int'."

A similar if-else construction works just fine.

Mihkel
 
As far as the ternary is concerned, it's two values are incompatible,
since "null" is interpreted as a null object, not the int? missing
value. You can re-educate it with a cast:

int? intVar = decVar == null ? (int?) null :
Convert.ToInt32(decVar.GetValueOrDefault());

Marc
 
you've to convert the null to a nullable int

decimal? decVar = 5;
int? intVar = decVar == null ? (int?)null :
Convert.ToInt32(decVar.GetValueOrDefault());
 
Just one question, why wouldn't the following lines compile:

decimal? decVar = 5;
int? intVar = decVar == null ? null :
Convert.ToInt32(decVar.GetValueOrDefault());

The compiler shows the following message: "There is no implicit conversion
between 'null' and 'int'."

A similar if-else construction works just fine.

An int isn't convertible to null, and null isn't convertible to int -
you need to explain to the compiler which type to use that both values
*can* be converted to:

int? intVar = decVar==null ? (int?) null : Convert.ToInt32(...);
or
int? intVar = decVar==null ? null : (int?)Convert.ToInt32(...);

Note that the code can be simplified somewhat:

However, for this code it's easier to just use:

int? intVar = (int?) decVar;

Jon
 
then how is this statement different from the first one i've presented:

int? intVar = null;

this would work just fine.
 
then how is this statement different from the first one i've presented:

int? intVar = null;

this would work just fine.

That's converting from null to int?, which is fine.

The conditional operator has to decide what the type of the overall
expression is. It does this by taking the two result types, and seeing
if it can convert from either one to the other. In this case, it
can't.

Jon
 
Marc Gravell said:
As far as the ternary is concerned, it's two values are incompatible,
since "null" is interpreted as a null object, not the int? missing
value. You can re-educate it with a cast:

int? intVar = decVar == null ? (int?) null :
Convert.ToInt32(decVar.GetValueOrDefault());

Furthermore (and to eliminate precedence confusion), don't compare Nullable
values to null.

Instead, use the HasValue property:

int? intVar = decVar.HasValue? Convert.ToInt32(decVar.GetValueOrDefault()):
(int?) null;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top