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 in C# serves two distinct syntactic roles depending on its context: as a binary Logical/Bitwise Exclusive OR (XOR) operator, and as a unary Index from End operator.

1. Logical and Bitwise Exclusive OR (XOR) Operator

When used as a binary operator between two operands, ^ computes the exclusive OR. The evaluation mechanics depend strictly on the operand types:
  • Boolean Operands (bool): Performs a logical XOR. It evaluates to true if and only if exactly one operand is true. If both operands share the same boolean value, it evaluates to false.
  • Integral Operands (int, uint, long, etc.): Performs a bitwise XOR. It compares the binary representations of the operands bit by bit, resulting in 1 where the corresponding bits differ, and 0 where they match.
// Logical XOR
bool logicalResult1 = true ^ false; // Evaluates to true
bool logicalResult2 = true ^ true;  // Evaluates to false

// Bitwise XOR
int bitwiseResult = 5 ^ 3;          // Evaluates to 6
/* Bitwise evaluation:
   0101 (5 in binary)
 ^ 0011 (3 in binary)

   0110 (6 in binary)
*/
The binary ^ operator also supports compound assignment via ^=, which applies the XOR operation and assigns the result to the left operand.
int value = 5;
value ^= 3; // Equivalent to: value = value ^ 3; (Evaluates to 6)

2. Index from End Operator

Introduced in C# 8.0, when used as a unary prefix operator, ^ instantiates a System.Index struct. It specifies an index relative to the end of a sequence (such as an array, Span<T>, or string), rather than the beginning. The index ^n translates to sequence.Length - n at runtime. Consequently, ^1 points to the last element in the sequence. ^0 points to the sequence length itself; while ^0 throws an IndexOutOfRangeException if used for direct element access, it is syntactically valid and required when defining an exclusive upper bound in a System.Range.
int[] numbers = { 10, 20, 30, 40, 50 };

// Direct indexing
int last = numbers[^1];         // Evaluates to 50 (numbers.Length - 1)
int secondToLast = numbers[^2]; // Evaluates to 40 (numbers.Length - 2)

// Range indexing (..) using Index from End
// Extracts from index 1 up to, but not including, the last element
int[] slice = numbers[1..^1];   // Evaluates to { 20, 30, 40 }
Master C# with Deep Grasping Methodology!Learn More