Return ulong inline-if

Is there a reason why I cannot use the following code?

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

This 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 a problem. I just want to know the reason.

Thanks.

+7
c # ternary-operator conditional-operator ulong
source share
3 answers

Let's look at the received 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 

In IL_0001 literally 1 is IL_0001 stack (therefore, the expression return false ? 0 : 1; evaluated at compile time and injected into IL as a constant), and in IL_0002 this literal is converted to 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 that the value of the constant expression is within the range of the target type.

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

+5
source share

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

The second example is a constant expression.

+2
source share

This will work:

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

See, the compiler infers the type from the size of the number, so if you need a specific type, you must specify a suffix. See the "Literals" section on this MSDN page.

Edit: As pointed out to me, this question was not looking for an answer on how to make it work. I believe that there is still some value in the MSDN article. It provides information that can explain why an unsuccessful event does not work, but not about why another one is failing. Really interesting problem.

0
source share

All Articles