Skip to main content
The %= operator is the compound remainder assignment operator. It divides the value of the left-hand operand by the value of the right-hand operand, computes the remainder, and assigns that resulting value back to the left-hand operand.

Syntax and Equivalence

This expression is semantically equivalent to:
where T is the type of x. The explicit cast (T) is required in the expanded form because of C#‘s numeric promotion rules. For example, if x and y are of type byte or short, the binary operation x % y yields an int. The compound assignment operator implicitly performs the cast back to the original type. A critical distinction in the compiler’s execution is that the left-hand operand (x) is evaluated only once. If x is a property access or an indexer with side effects, those side effects occur only a single time.

Type Support and Evaluation Rules

The %= operator is predefined for all standard numeric types in C#. Its behavior depends on the underlying types of the operands:
  • Integer Types (int, long, etc.): Computes the standard mathematical remainder. If the right-hand operand is 0, the runtime throws a DivideByZeroException.
  • Floating-Point Types (float, double): Computes the remainder using a truncating division. This explicitly differs from the IEEE 754 remainder specification, which uses a rounding division (available in C# via Math.IEEERemainder). If the right-hand operand is 0.0, the operation does not throw an exception; instead, it assigns NaN (Not a Number) to the left operand.
  • Decimal Type (decimal): Computes the remainder with higher precision. Similar to integer types, if the right-hand operand is 0m, it throws a DivideByZeroException.

Code Visualization

Operator Overloading

You cannot explicitly overload the %= operator in a user-defined struct or class. However, C# automatically supports compound assignment for custom types if you overload the binary remainder operator (%).
Tired of Poor C# Skills? Fix That With Deep Grasping!Learn More