Lehks
Lehks

Reputation: 3166

C# - what does the unary ^ do?

I have checked out some code and I got an error ('invalid expression term "^"' to be exact) in the line

// choices is a regular array
return choices[^1];

I have never seen a unary caret operator (I am only aware of the XOR operator, but that one obviously takes two operands). Does this operator exist and if so, what does it do?

Note: The site https://www.tutorialsteacher.com/csharp/csharp-operators mentions a unary caret operator in the precedence table but it does not explain what it does.

Upvotes: 23

Views: 5878

Answers (2)

D A
D A

Reputation: 2054

In arrays it is called "Index from end operator" and is available from C# 8.0. As it says ... it indicates the element position from the end of a sequence.

In the second case, ^ plays the role of Logical exclusive OR operator. Being a binary operator, it needs two members (x ^ y), because it is doing an operation on them. As an example:

Console.WriteLine(true ^ true);    // output: False
Console.WriteLine(true ^ false);   // output: True
Console.WriteLine(false ^ true);   // output: True
Console.WriteLine(false ^ false);  // output: False

Upvotes: 1

Mureinik
Mureinik

Reputation: 311428

Unary ^ is the "index from end" operator, introduced in C# 8.0. choices[^1] is equivalent to choices[choices.Length - 1].

See the official documentation for additional details.

Upvotes: 35

Related Questions