Why can't a C # compiler pass a literal negative value to an enumeration?

This code does not compile with the latest C # compiler :

public class Program
{
    public static void Main()
    {
        IntEnum a = (IntEnum)-1;
    }
}

public enum IntEnum : int { }

When you try to compile it, it raises

(3,22,3,29): Error CS0119: "IntEnum" is a type that is not valid in this context

Oddly enough, changing the cast value to a positive number (for example 4) or using the const value (for example int.MinValue) or even the surrounding value using parentheses such as (IntEnum)(-1)will compile and work just fine. However, the above sample does not work.

Is there a reason for this? Is it possible that Roslyn may be parsing the code incorrectly, and why does the error occur?

+4
1

, (Var)-1.

CS0075 ( , CS0119):

, , , . , (x) -y . #, 7.6.6:

, x y , (x) y, (x) (y) (x) (- y) , (x) -y , , x . , x - , (, int), - ( ).

+6

Source: https://habr.com/ru/post/1652124/


All Articles