James Ko James Ko - 2 months ago 9x
C# Question

Why isn't the C# compiler able to cast a literal negative value to an enum?

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 attempt to compile it, it raises

(3,22,3,29): Error CS0119: 'IntEnum' is a type, which is not valid in the given context

Strangely, changing the casted value to a positive number (such as
), or using a const value (such as
), or even surrounding the value with parentheses like
will compile and work just fine. However, the above sample does not.

Is there any reason for this? Is it possible that Roslyn is perhaps parsing the code incorrectly, and that's why an error is getting raised?


Behavior is expected and documented to allow expressions like (Var)-1 to be parsed.

Compiler Error CS0075 goes into spec details (I would expect you to get that error instead/in addition to CS0119):

To cast a negative value, you must enclose the value in parentheses If you are casting using a keyword that identifies a predefined type, then you do not need parentheses. Otherwise, you must put the parentheses because (x) –y will not be considered a cast expression. From the C# Specification, Section 7.6.6:

From the disambiguation rule it follows that, if x and y are identifiers, (x)y, (x)(y), and (x)(-y) are cast-expressions, but (x)-y is not, even if x identifies a type. However, if x is a keyword that identifies a predefined type (such as int), then all four forms are cast-expressions (because such a keyword could not possibly be an expression by itself).