Getting Setup With C# 8
If you aren’t sure if you are using C# 8, or you know you aren’t and want to know how to access these features. Read this quick guide on getting setup with .NET Core and C# 8.
Have You Seen Ranges Yet?
The Index struct is pretty similar to ranges which also made it into C#. If you haven’t already, go check out the article on Ranges in C# 8 here.
It’s not a pre-requisite to know ranges before you use the new Index type, but it’s probably a pretty good primer and they share the new “hat” ^ character.
Overview
If you wanted to get the last item of an array, you would typically see code like this :
var integerArray = new int[3]; integerArray[0] = 1; integerArray[1] = 2; integerArray[2] = 3; var lastItem = integerArray[integerArray.Length - 1];
If you wanted second to last you would end up doing something like :
var lastItem = integerArray[integerArray.Length - 2];
If you have a List<T>, you would have a couple of different options, mostly involving Linq. So something like this :
var integerList = integerArray.ToList(); integerList.Last();
But with arrays, what we notice is that we are still always counting from the front. So we are passing in that we want index 2, not that we want the last index persay.
With C# 8 however, we have the ability to do this :
var lastItem = integerArray[^1];
So we can pass in the “hat” character, and this signifies that we are looking for the index X away from the end of the array. You’ll also notice something very important. Whereas junior developers have struggled since the dawn of time to wrap their head around arrays starting at index “0”. When we use the hat character, we are saying we want to count from the end but inclusive. So saying ^1 means the last index, not the second to last index. Weird I know.
And that’s the new index character in a nutshell!
Index As A Type
When you say ^1, you are actually creating a new struct in C# 8. That struct being Index. For example :
var index = new Index(1, true); Index indexStruct = ^1; var indexShortHand = ^1;
All of these create a new struct of Index that hold a value of the last index item.
You might want to use it in this way if you have a particular count from the end that you want to re-use on multiple arrays.
Index Is Simple
The index type is actually really simple. If you take a look at the source code, you’ll see really all it is, is an integer value held inside a struct wrapper.