What does `array[^1]` mean in C# compiler? [duplicate]
Asked Answered
E

1

27
int[] numbers = new int[10];
numbers[9] = 10;
Console.Write(numbers[^1] == numbers[numbers.Count()-1]); //true

How does index of ^1 returns the last item in an array?

What does ^1 mean in C# compiler?

Does it have performance benefit vs numbers[numbers.Count()-1]?

Elsy answered 26/10, 2020 at 9:57 Comment(5)
Perhaps you should read the docs? learn.microsoft.com/en-us/dotnet/csharp/language-reference/…. Also, it's obviously better than using numbers.Count()-1 since Count() is a Linq method that needs to iterate through the entire array.Weeping
@CamiloTerevinto: Enumerable.Count() is a little smarter than that -- if applied to anything that implements ICollection (which includes arrays) it will just get the .Count of that. There's still overhead, but far less than if the whole array had to be iterated.Unaccustomed
@JeroenMostert I'm very aware of that, but that's an implementation detail that can change in the future :)Weeping
Okay this is C# 8 feature, but what is equivalent code for this in C# 7? What is ^1 translated to?Elsy
that's all well described in Camilo Terevinto's link...Toughen
D
61

numbers[^1] is the same with numbers[length-1]

They are called ranged operators in C# 8. Check this link for more details.

Data answered 26/10, 2020 at 12:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.