Search code examples
c#language-lawyerpostfix-operatorprefix-operator

Why is it illegal to use both prefix and postfix at the same time?


Why is the following code illegal?

using System;

class Program
{
    static void Main(string[] args) {
        int i = 0;
        --i++;
        Console.WriteLine(i);
    }
}

It gives me the following error on the --i++:

The operand of an increment or decrement operator must be a variable, property or indexer

I know that this code has no practical use; I'm merely curious why it is not allowed. I don't care that it can be fixed by removing that line with no other effects. As this is tagged with , please include evidence from the language specification.


Solution

  • From the C# specification "7.6.9 Postfix increment and decrement operators":

    The operand of a postfix increment or decrement operation must be an expression classified as a variable, a property access, or an indexer access. The result of the operation is a value of the same type as the operand.

    I think this answers your question.

    It's also the reason you can't do i++++, nor with parentheses: (i++)++ gives the same compilation error as well.