Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 4), or using a const value (such as int.MinValue), or even surrounding the value with parentheses like (IntEnum)(-1) 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?

like image 994
James Ko Avatar asked Aug 23 '16 02:08

James Ko


People also ask

Why is C not A or B?

Because C comes after B The reason why the language was named “C” by its creator was that it came after B language. Back then, Bell Labs already had a programming language called “B” at their disposal.

Is C still used in 2022?

Let's say you are new to programming. There are a variety of languages to choose from. Many people will recommend Python as your first language because of its short syntax which makes it very attractive.

What <> means in C?

<> in some languages means "does not equal". But in c, the operator is != . Also note the difference between logical AND ( && ) and bitwise AND ( & ). You should use the logical operators for multiple criteria in a conditional statement.

Is C still worth using?

Is Learning C Worth It? Learning C is worth it. It is hard to avoid C because it is used to write OS kernels, databases, compilers, and many other applications. Knowledge of C will be required to debug or improve them.


1 Answers

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).

like image 187
Alexei Levenkov Avatar answered Nov 03 '22 09:11

Alexei Levenkov