170

The following code is wrong (see it on ideone):

public class Test
{
    public static void Main()
    {
        int j = 5;
        (j++);      // if we remove the "(" and ")" then this compiles fine.
    }
}

error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement

  1. Why does the code compile when we remove the parentheses?
  2. Why does it not compile with the parentheses?
  3. Why was C# designed that way?
12
  • 29
    @Servy lots of people involved with C# language design are on SO, so thats why I asked. Anything wrong with this?
    – user10607
    Commented Dec 22, 2015 at 18:28
  • 34
    I can't imagine a more on-topic question than "why does a specific programming language handle this specific behavior in this way?"
    – Mage Xy
    Commented Dec 22, 2015 at 18:33
  • 20
    Now we have an answer of Eric Lippert. Maybe you want to re-think your decision about the accepted answer. It's Christmas, so perhaps you have accepted the answer too early. Commented Dec 22, 2015 at 21:03
  • 17
    @Servy Are you implying that design decisions are never documented and are absolutely unknown to everyone else? He's not asking SO users to guess, he's asking for an answer - that does not imply he's asking for a guess. Whether people answer with a guess is on them, not him. And as OP pointed out, there are people on stack overflow who did actually work on C# and made these decisions.
    – Rob
    Commented Dec 22, 2015 at 23:04
  • 5
    @Rob: The problem is that, yes, unless the rationale is already documented somewhere, it must, but speculation is fun and who doesn't want to share his own? If you find a way to make sure such pure (or "educated") guesses are reliably culled, tell me and we'll make a fortune. Commented Dec 23, 2015 at 1:46

3 Answers 3

222

Deep insights appreciated.

I shall do my best.

As other answers have noted, what's going on here is the compiler is detecting that an expression is being used as a statement. In many languages -- C, JavaScript, and many others -- it is perfectly legal to use an expression as a statement. 2 + 2; is legal in these languages, even though this is a statement that has no effect. Some expressions are useful only for their values, some expressions are useful only for their side effects (such as a call to a void returning method) and some expressions, unfortunately, are useful for both. (Like increment.)

Point being: statements that consist only of expressions are almost certainly errors unless those expressions are typically thought of as more useful for their side effects than their values. C# designers wished to find a middle ground, by allowing expressions that were generally thought of as side-effecting, while disallowing those that are also typically thought of as useful for their values. The set of expressions they identified in C# 1.0 were increments, decrements, method calls, assignments, and somewhat controversially, constructor invocations.


ASIDE: One normally thinks of an object construction as being used for the value it produces, not for the side effect of the construction; in my opinion allowing new Foo(); is a bit of a misfeature. In particular, I've seen this pattern in real-world code that caused a security defect:

catch(FooException ex) { new BarException(ex); } 

It can be surprisingly hard to spot this defect if the code is complicated.


The compiler therefore works to detect all statements that consist of expressions that are not on that list. In particular, parenthesized expressions are identified as just that -- parenthesized expressions. They are not on the list of "allowed as statement expressions", so they are disallowed.

All of this is in service of a design principle of the C# language. If you typed (x++); you were probably doing something wrong. This is probably a typo for M(x++); or some just thing. Remember, the attitude of the C# compiler team is not "can we figure out some way to make this work?" The attitude of the C# compiler team is "if plausible code looks like a likely mistake, let's inform the developer". C# developers like that attitude.

Now, all that said, there actually are a few odd cases where the C# specification does imply or state outright that parentheses are disallowed but the C# compiler allows them anyways. In almost all those cases the minor discrepancy between the specified behaviour and the allowed behaviour is completely harmless, so the compiler writers have never fixed these small bugs. You can read about those here:

Is there a difference between return myVar vs. return (myVar)?

7
  • 5
    Re: "One normally thinks of a constructor invocation as being used for the value it produces, not for the side effect of the construction; in my opinion this is a bit of a misfeature": I'd imagine that one factor in this decision was that if the compiler forbade it, there wouldn't be any clean fix in cases where you are calling it for a side-effect. (Most other forbidden expression statements have extraneous parts that serve no purpose and can be removed, with the exception of ... ? ... : ..., where the fix is to use if/else instead.)
    – ruakh
    Commented Dec 22, 2015 at 23:59
  • 1
    @ruakh: Since this is behavior that should be discouraged, a clean fix is not necessary, so long as there is a reasonably cheap/simple fix. Which there is; assign it to a variable and don't use that variable. If you want to be blatant that you aren't using it, give that line of code it's own scope. While technically one could argue that this changes the code's semantics (a useless reference assignment is still a useless reference assignment), in practice it is unlikely to matter. I admit that it does generate slightly different IL... but only if compiled without optimizations.
    – Brian
    Commented Dec 23, 2015 at 14:43
  • Safari, Firefox, and Chrome all give ReferenceError when typing contineu;. Commented Dec 23, 2015 at 23:48
  • 2
    @McBrainy: You're right. I am misremembering the defect that results from the misspelling; I'll check my notes. In the meanwhile I've deleted the offending statement as it is not germane to the larger point here. Commented Dec 24, 2015 at 0:40
  • 1
    @Mike: I agree. Another situation in which we sometimes see the statement is test cases like try { new Foo(null); } catch (ArgumentNullException)... but obviously these situations are by definition not production code. It seems reasonable that such code could be written to assign to a dummy variable. Commented Jan 4, 2016 at 20:26
46

In the C# language specification

Expression statements are used to evaluate expressions. Expressions that can be used as statements include method invocations, object allocations using the new operator, assignments using = and the compound assignment operators, increment and decrement operations using the ++ and -- operators and await expressions.

Putting parentheses around a statement creates a new so-called parenthesized expression. From the specification:

A parenthesized-expression consists of an expression enclosed in parentheses. ... A parenthesized-expression is evaluated by evaluating the expression within the parentheses. If the expression within the parentheses denotes a namespace or type, a compile-time error occurs. Otherwise, the result of the parenthesized-expression is the result of the evaluation of the contained expression.

Since parenthesized expressions are not listed as a valid expression statement, it is not a valid statement according to the specification. Why the designers chose to do it this way is anyone's guess but my bet is because parentheses do no useful work if the entire statement is contained in parentheses: stmt and (stmt) are exactly the same.

7
  • 4
    @Servy: If you read closely, it was slightly more nuanced than that. The so-called "Expression Statement" is indeed a valid statement, and the specification lists the types of expressions that can be valid statements. However, I repeat from the spec that the type of expression called the "parenthesized expression" is NOT on the list of valid expressions which can be used as valid expression statements. Commented Dec 22, 2015 at 18:55
  • 4
    The OP is asking nothing about the language design. He just wants to know why this is an error. The answer is: because it is not a valid statement.
    – Leandro
    Commented Dec 22, 2015 at 19:15
  • 9
    OK, my bad. The answer is: because, according to the specification, it is not a valid statement. There you have it: a design reason!
    – Leandro
    Commented Dec 22, 2015 at 19:27
  • 3
    The question is not asking for a deep, design-driven reason as to why the language was designed to handle this syntax in this way - he's asking why one piece of code compiles when another piece of code (which to beginners looks like it should behave identically) fails to compile. This post answers that.
    – Mage Xy
    Commented Dec 22, 2015 at 19:55
  • 4
    @Servy JohnCarpenter isn't just saying "You can't do that." He's saying, those two things you were confused by aren't the same. j++ is an Expression Statement, while (j++) is a parenthesized-expression. All of a sudden the OP now knows the difference and what they are. That is a good answer. It answers the body of his question not the title. I think a lot of contention comes from the word "design" in the title of the question, but this doesn't have to be answered by the designers, just gleaned from the specifications.
    – thinklarge
    Commented Dec 22, 2015 at 20:05
19

beacause the brackets around the i++ are creating/defining an expression.. as the error message says.. a simple expression cant be used as a statement.

why the language was designed to be this way? to prevent bugs, having misleading expressions as statements, that produce no side effect like having the code

int j = 5;
j+1; 

the second line has no effect(but you may not have noticed). But instead of the compiler removing it(because the code is not needed).it explicitly asks you to remove it(so you will be aware or the error) OR fix it in case you forgot to type something.

edit:

to make the part about bracked more clear.. brackets in c# (besides other uses, like cast and function call), are used to group expressions, and return a single expression (make of the sub expressions).

at that level of code only staments are allowed.. so

j++; is a valid statement because it produces side effects

but by using the bracked you are turning it into as expression

myTempExpression = (j++)

and this

myTempExpression;

is not valid because the compiler cant asure that the expression as side effect.(not without incurring into the halting problem)..

3
  • Yeah, that's what I thought at first too. But this does have a side effect. It performs post–increment of j variable right?
    – user10607
    Commented Dec 22, 2015 at 18:36
  • 1
    j++; is a valid statement, but by using the brackets you are saying let me take this stement and turn it into an expression.. and expresions are not a valid at that point in code
    – CaldasGSM
    Commented Dec 22, 2015 at 18:39
  • It's too bad there's no form of "compute and ignore" statement, since there are occasions when code may wish to assert that a value can be computed without throwing an exception, but not care about the actual value thus computed. A compute-and-ignore statement wouldn't be used terribly often, but would make the programmer's intention clear in such cases.
    – supercat
    Commented Dec 23, 2015 at 23:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.