Why does this implicit conversion from int to uint work?

后端 未结 3 1356
再見小時候
再見小時候 2020-12-17 17:25

Using Casting null doesn't compile as inspiration, and from Eric Lippert\'s comment:

That demonstrates an interesting case. \"uint x = (int)0;\" w

相关标签:
3条回答
  • 2020-12-17 17:31

    Integer constant conversions are treated as very special by the C# language; here's section 6.1.9 of the specification:

    A constant expression 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. A constant expression of type long can be converted to type ulong, provided the value of the constant expression is not negative.

    This permits you to do things like:

    byte x = 64;
    

    which would otherwise require an ugly explicit conversion:

    byte x = (byte)64; // gross
    
    0 讨论(0)
  • 2020-12-17 17:49

    In general compilers have 4 steps in which the code is converted. Text is tokenized > Tokens are parsed > An AST is built + linking > the AST is converted to the target language.

    The evaluation of constants such as numbers and strings occurs as a first step and the compiler probably treats 0 as a valid token and ignores the cast.

    0 讨论(0)
  • 2020-12-17 17:53

    The following code wil fail with the message "Cannot implicitly convert type 'int' to 'uint'. An explicit conversion exists (are you missing a cast?)"

    int y = 0;
    uint x = (int)y;
    

    And this will fail with: "Constant value '-1' cannot be converted to a 'uint'"

    uint x = (int)-1;
    

    So the only reason uint x = (int)0; works is because the compiler sees that 0 (or any other value > 0) is a compile time constant that can be converted into a uint

    0 讨论(0)
提交回复
热议问题