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 functions 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)

As a binary operator, ^ evaluates the exclusive OR of its operands. It is supported for boolean types and integral numeric types. Boolean Operands: When applied to bool operands, ^ computes the logical exclusive OR. It evaluates to true if and only if exactly one operand evaluates to true. If both operands evaluate to the same value, the result is false. Unlike the conditional logical operators (&&, ||), the ^ operator always evaluates both operands; it does not short-circuit.
bool result1 = true ^ false;  // Evaluates to true
bool result2 = true ^ true;   // Evaluates to false
bool result3 = false ^ false; // Evaluates to false
Integral Numeric Operands: When applied to integral types (int, uint, long, ulong, byte, etc.), ^ computes the bitwise exclusive OR. It compares the binary representation of both operands bit by bit. The resulting bit is set to 1 if the corresponding bits in the operands are different, and 0 if they are identical.
int a = 5;     // Binary: 0000 0101
int b = 3;     // Binary: 0000 0011
int c = a ^ b; // Binary: 0000 0110 (Evaluates to 6)
Compound Assignment: The ^ operator can be combined with the assignment operator to form ^=. This applies the XOR operation to the left and right operands and assigns the resulting value to the left-hand variable.
int x = 5;
x ^= 3; // Equivalent to: x = x ^ 3; (x evaluates to 6)

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

As a unary prefix operator, ^ instantiates a System.Index struct representing an offset relative to the end of a sequence (such as an array, Span<T>, or string). The index ^n is mathematically translated by the compiler to sequence.Length - n. Because C# uses zero-based indexing from the start, the index ^0 equals the sequence length (which throws an IndexOutOfRangeException if used for direct element access), and ^1 represents the final element in the sequence.
int[] numbers = { 10, 20, 30, 40, 50 };

// Evaluates to numbers[numbers.Length - 1]
int lastElement = numbers[^1];      // 50

// Evaluates to numbers[numbers.Length - 2]
int secondToLast = numbers[^2];     // 40

// Explicitly instantiating a System.Index type
Index indexFromEnd = ^3;            
int middleElement = numbers[indexFromEnd]; // 30
Master C# with Deep Grasping Methodology!Learn More