Tech moves fast! Stay ahead of the curve with Techopedia!
Join nearly 200,000 subscribers who receive actionable tech insights from Techopedia.
A decrement operator, in the context of C#, is a unary operator. It returns a value of same type, with predefined value equal to the operand value minus one. The decrement operator is denoted by the symbol '—'.
A decrement operator supports both prefix and postfix notations. In case of prefix notation (denoted by --x, where x is a variable), the value of a variable is used in the expression after decrementing its original value. While using postfix notation (x--), the value of a variable before the decrement operation will be considered in the expression. A decrement operator can be used to change the pointer location by subtracting a value equal to the size (or pointer-type) from the address contained in the pointer variable.
A decrement operator is usually used in loop iteration statements or in any context where there is a need to decrement by one unit. Features of decrement operator include:
Note that, while using a decrement operator, the operand must be an expression representing a variable, property access, or indexes. Additionally, If the decrement operator is used with prefix notation for operand, the property or indexer must have a get and set accessor to avoid compilation errors. Furthermore, if a decrement operator is used for a pointer, the pointer can be of any type except void*.
A decrement operator should be used to set a variable and not to a value. Usage of a decrement operator more than once in a single expression can cause unpredictable results mostly because of optimization applied by the compiler. Hence, it is suggested to use a decrement operator after understanding the order of evaluation, while using both postfix and prefix notation along with its precedence in the set of C# operators. Postfix and prefix notations of a decrement operator cannot have separate operator implementation.