14
        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]?

Hassan Monjezi
  • 1,060
  • 1
  • 8
  • 24
  • 4
    Perhaps you should read the docs? https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/ranges#runtime-behavior. Also, it's obviously better than using `numbers.Count()-1` since `Count()` is a Linq method that needs to iterate through the entire array. – Camilo Terevinto Oct 26 '20 at 10:00
  • 4
    @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. – Jeroen Mostert Oct 26 '20 at 10:03
  • @JeroenMostert I'm very aware of that, but that's an implementation detail that can change in the future :) – Camilo Terevinto Oct 26 '20 at 10:04
  • Okay this is C# 8 feature, but what is equivalent code for this in C# 7? What is `^1` translated to? – Hassan Monjezi Oct 26 '20 at 10:19
  • that's all well described in Camilo Terevinto's link... – Patrick Beynio Oct 26 '20 at 10:31

1 Answers1

35

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

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

user3026017
  • 569
  • 4
  • 10