Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The *= operator is the compound multiplication assignment operator. It multiplies the current value of the left-hand operand by the value of the right-hand operand and assigns the resulting product back to the left-hand operand.

Syntax and Evaluation

x *= y;
This expression is semantically equivalent to:
x = x * y;
However, there is a strict evaluation difference: in the *= operation, the left-hand operand x is evaluated exactly once. If x is an expression with side effects, such as an array access where the index is determined by a method call, the method is invoked only once.
int[] arr = { 2, 4, 6 };

static int GetIndex() => 1;

// GetIndex() is called exactly once, not twice.
arr[GetIndex()] *= 5; 

Type Promotion and Implicit Casting

A critical mechanical feature of the *= operator is its handling of numeric type promotion. In C#, arithmetic operations on types smaller than 32 bits (byte, sbyte, short, ushort, char) automatically promote the operands to int. Using the standard assignment (x = x * y) requires an explicit cast to narrow the int result back to the original type. The *= operator handles this underlying cast automatically.
byte a = 10;
byte b = 2;

// Compiles successfully. The compiler evaluates this as: a = (byte)(a * b);
a *= b;

// Compilation error: Cannot implicitly convert type 'int' to 'byte'.
// a = a * b; 

Operator Overloading

The *= operator cannot be explicitly overloaded in C#. Instead, it is implicitly evaluated using the binary multiplication operator (*). If a custom class or struct overloads the * operator, the *= operator automatically becomes available and utilizes that custom implementation.
Matrix m = new Matrix(5);
m *= 3; // Valid. Evaluates using the overloaded '*' operator.

public readonly struct Matrix
{
    public readonly int Value;
    public Matrix(int value) => Value = value;

    // Overloading '*' implicitly provides '*=' functionality
    public static Matrix operator *(Matrix left, int right) 
    {
        return new Matrix(left.Value * right);
    }
}

Thread Safety and Atomicity

The *= operator is not an atomic operation. It executes as a multi-step read-modify-write sequence:
  1. Read the value of the left operand.
  2. Multiply it by the right operand.
  3. Write the result back to the memory location of the left operand.
Because it is not atomic, applying *= to a shared variable across multiple threads without synchronization (such as a lock statement) will result in race conditions. Unlike addition or increment operations, the System.Threading.Interlocked class does not provide a built-in method for atomic multiplication.
Master C# with Deep Grasping Methodology!Learn More