Sam Watson
Sam Watson

Reputation: 31

UInt weird compile time behaviour - returning a Long..?

The following code prints UInt32:

var myUint = 1U;
Console.WriteLine(myUint.GetType().Name);

As per this SO answer I wanted to see what would happen if you try to use the U literal suffix with a compile-time negative number. This code (changing1U to -1U) prints Int64 (long):

var myUint = -1U;
Console.WriteLine(myUint.GetType().Name);

I thought it would just be a compile time error, but instead returns a long with the value -1 - what is going on? Why does the compiler do this??

Upvotes: 3

Views: 112

Answers (2)

CodeCaster
CodeCaster

Reputation: 151604

The minus sign is not a part of the integer literal specification. So when you write var x = -1U, the following rules are applied by the compiler:

If the literal is suffixed by U or u, it has the first of these types in which its value can be represented: uint, ulong.

So that's the 1U part becoming a uint / UInt32, so far conforming to your expectations.

But then the minus is applied:

For an operation of the form -x, unary operator overload resolution (§7.3.3) is applied to select a specific operator implementation. The operand is converted to the parameter type of the selected operator, and the type of the result is the return type of the operator. The predefined negation operators are:

  • Integer negation:

    int operator -(int x);

    long operator -(long x);

[...]

If the operand of the negation operator is of type uint, it is converted to type long, and the type of the result is long.

So the type of the expression -1U is long, as per the C# specification. This then becomes the type of x.

Upvotes: 3

Michal B.
Michal B.

Reputation: 5719

Obviously -1U cannot be stored as a uint. Since you use var, the compiler deduces the type to hold the value. Since you want to hold -(1 as unsigned integer), the compiler decides to store it as long.

You would get a compile time error if you defined your type explicitly:

uint myUint = -1U;

Upvotes: 0

Related Questions