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?
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.
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.
<> 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 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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With