Why should I specify (int?) In C # when the type of the variable is [int?]

Can someone explain to me the logical reason why I should be casting null

inint?

Should the type of the left argument be both types?

Performed

  int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : null);

      

I must do

  int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);

      

although it int? k = null

works great.

Opposite example:

I didn't need to do this:

string k = (DateTime.Now.Ticks%5 > 3 ? "lala" : null);

+3


source to share


2 answers


int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);

      

In this case we have 1: int

and null

in fact null

now the confusion is the ternary operator that gets confused as a return type int

or good null

and since it int

won't accept itnull

So you will need to cast it back to a nullable value int



Now otherwise you have a string and null is perfectly acceptable for string

Further explanation can be found at Output Type - Eric

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

  • If X and Y are the same type, then this is the type of the conditional expression.

  • Otherwise, if the implicit conversion exists from X to Y but not Y to X, then Y is the type of the conditional expression.

  • Otherwise, if the implicit conversion exists from Y to X, but not from X to Y, then X is the type of the conditional expression.

  • Otherwise, the type of the expression cannot be determined and a compile-time error occurs.

+10


source


Because the compiler does not use the type of the variable on the left to determine the type of the expression on the right. It first determines the type of the expression, then it determines if it can be put into a variable.

There is no type close enough to int

and null

. You must either make the int

value nullable or null

"intable" for the compiler to find a common basis for values.



When you have a value string

and null

, the compiler can simply use one of the types, because the string is already zeroed out.

+2


source







All Articles