Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return ulong in inline-if [duplicate]

Is there a reason why I can't use the following code?

ulong test(int a, int b)
{
    return a == b ? 0 : 1;
}

It shows me:

Cannot implicitly convert type 'int' to 'ulong'. An explicit conversion exists (are you missing a cast?)

The following will work:

ulong test(int a, int b)
{
    return false ? 0 : 1;
}

I know how to solve the problem. I just want to know the reason.

Thanks.

like image 505
Marcel Niehüsener Avatar asked Sep 30 '15 16:09

Marcel Niehüsener


2 Answers

Let's take a look at the resulting IL code of the second method:

IL_0000:  nop
IL_0001:  ldc.i4.1
IL_0002:  conv.i8
IL_0003:  stloc.0
IL_0004:  br.s       IL_0006
IL_0006:  ldloc.0
IL_0007:  ret

At IL_0001 the literal 1 is pushed onto the stack (so the expression return false ? 0 : 1; is evaluated at compile-time and embedded into IL as a constant) and at IL_0002 this literal is converted into an Int64.

From MSDN:

A constant-expression (Section 7.15) of type int can be converted to type sbyte, byte, short, ushort, uint, or ulong, provided the value of the constant-expression is within the range of the destination type.

Since 1 is in the range of the ulong data type, such conversion will always succeed. The compiler knows that and therefore performs an implicit conversion.

like image 174
Kapol Avatar answered Oct 14 '22 23:10

Kapol


Variables typed as int cannot be implicitly converted to ulong, because an int can represent a negative value, while a ulong cannot. A constant can be implicitly converted, provided that the value of the constant expression is non-negative.

Your second example is a constant expression.

like image 43
phoog Avatar answered Oct 15 '22 01:10

phoog