TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
^= operator is the compound assignment operator for the exclusive OR (XOR) operation. It evaluates the XOR operation between the left-hand and right-hand operands, and subsequently assigns the resulting value back to the left-hand operand.
Syntax
^=), the left-hand operand x is evaluated only once. This is significant when x is a property access or an indexer with side effects (e.g., array[GetIndex()] ^= value;), ensuring the side effect occurs only one time.
Operational Mechanics
The behavior of the^= operator depends strictly on the data types of its operands. It applies to integral numeric types, booleans, enumerations, and types implementing specific operator overloads or generic interfaces.
Bitwise XOR (Integral and Enumeration Types)
When applied to integral numeric types (int, uint, long, ulong, short, ushort, byte, sbyte, char, nint, nuint), the operator performs a bitwise XOR on the binary representations of the operands.
For each corresponding bit position, the operator yields:
1if the bits are different.0if the bits are identical.
enum), including those decorated with the [Flags] attribute, the operator performs the bitwise XOR operation on the underlying integral type of the enumeration.
Logical XOR (Boolean Types)
When applied tobool operands, the operator performs a logical strict disjunction. It evaluates to true if and only if the operands have different boolean values.
true ^= falseyieldstruefalse ^= trueyieldstruetrue ^= trueyieldsfalsefalse ^= falseyieldsfalse
Operator Overloading and Generic Math
The^= operator itself cannot be explicitly overloaded. However, if a user-defined type (class or struct) overloads the binary ^ operator, the ^= compound assignment is automatically supported and evaluated using that overload. The left-hand operand is reassigned to the new instance returned by the overloaded operator.
^= operator is natively supported by any type that implements the IBitwiseOperators<TSelf, TOther, TResult> interface via Generic Math, allowing the operator to be used in generic contexts where the type parameter is constrained to this interface.
Type Promotion and Casting
When using^= with smaller integral types (like byte or short), C# applies implicit numeric promotion. The operands are widened to int before the XOR operation occurs.
The ^= operator automatically handles the required explicit cast back to the original type of the left-hand operand, provided the operation is valid.
b = b ^ 2; (since b ^ 2 evaluates to an int and cannot be implicitly converted back to a byte).
Master C# with Deep Grasping Methodology!Learn More





