Search code examples
c#classoperator-keyword

How to use increment and decrement operators for 'this' keyword?


I've been making a class in C#, but then I've faced an issue.

I implemented ++ and -- operators (also known as increment and decrement operators) to the class.

But then, in one function I had to use this++; and this--;. However, this causes an error: 'The operand of the increment or decrement operator must be a variable, property, or indexer'.

Is there any way to use these operators for this keyword?


Solution

  • C# complains when you are trying to apply these operators to this if the object is a class, because then this is a reference to the current object and you cannot assign it another value (and x++ usually means x = x + 1).

    this++; works, however, if the object is a struct, because you can copy the values of another struct to the current struct with this = otherStruct;

    A workaround is to assign this to a temp:

    var x = this;
    x++;
    

    The uneasy feeling, however, remains with this operation (See Jon Skeet's comment above). What are you trying to achieve?