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 purposes 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. It evaluates to true (or 1) if and only if exactly one of the operands is true (or 1). If both operands are the same, it evaluates to false (or 0). Logical XOR (Boolean Operands) For bool operands, the ^ operator computes the logical exclusive OR. Unlike the conditional logical operators (&&, ||), the ^ operator always evaluates both operands; it does not short-circuit.
bool a = true ^ false;  // Evaluates to true
bool b = true ^ true;   // Evaluates to false
bool c = false ^ false; // Evaluates to false
Bitwise XOR (Integral Operands) For integral numeric types (int, uint, long, ulong, byte, sbyte, short, ushort), the ^ operator computes the bitwise exclusive OR of the corresponding bits of the two operands.
int x = 5;      // Binary: 0101
int y = 3;      // Binary: 0011
int z = x ^ y;  // Binary: 0110 (Evaluates to 6)

2. Index from End Operator (C# 8.0+)

When used as a unary prefix operator, ^ instantiates a System.Index struct representing an offset from the end of a sequence (such as an array, Span<T>, or string). The index ^n translates to the sequence’s Length - n. Therefore, ^1 points to the last element in the sequence. ^0 points to the sequence length itself, which will throw an IndexOutOfRangeException if used for direct element access, but is valid when used as the upper bound in a Range (..) expression.
int[] sequence = { 10, 20, 30, 40, 50 };

// Element access
int last = sequence[^1];        // Evaluates to 50 (sequence.Length - 1)
int secondToLast = sequence[^2]; // Evaluates to 40 (sequence.Length - 2)

// Range expression usage
int[] subSequence = sequence[..^1]; // Evaluates to { 10, 20, 30, 40 }
Underlying Type Evaluation The compiler translates the ^ prefix into a call to the System.Index constructor, passing the integer value and a boolean indicating that the index is from the end.
Index idx = ^3; 
// Equivalent to: Index idx = new Index(3, fromEnd: true);
Master C# with Deep Grasping Methodology!Learn More