C# 8 – Introducing Index struct and a brand new usage for the hat operator

We have been talking about C# 8 a lot lately. We have talked about how interpolated verbatim strings are being simplified (here), how default interface methods are being introduced (here) and we have many many more features to discuss about as C# 8 is introducing a lot of new and useful stuff.

For today we are going to talk about the Hat Operator. So far the Hat Operator (^) has been used as XOR operator for boolean types and bitwise XOR operator byte/integral types.
In C# 8 it will have a new usage.

So basically the new usage of this operator is to automatically create a instance of the Index struct. What is an Index struct you ask? Well that is also introduced in C# 8.
The code for the Index struct (as all of C# for that matter) is available on github here
You can see that it is a fairly simple struct that holds an integer value inside a boolean value to define if it should be counting from the end.
This helps with accessing arrays a lot easier than usual. We can easily store that value in a type of Index instead of an integer which defines our intent a lot clearly than a simple integer and helps with avoiding the misuse of that variable.

So far we have always been thinking from the start whan trying to access a value at a specific index in an array. So how does the hat operator help us?
Well if for example you wanted the last element in an array whose size was known, you would usually substract one from the size and use that magic or hardcoded number when indexing.

e.g.

You could use the array’s provided variables as in the following example:

This would also be of use in arrays of unknown length at compile time. Also it is usually the preferred case as it shows intent that you wish for the last item to be retrieved a lot easier, rather than having to count to see which is the fourth item and verify that it is the last one.

Well using the Index struct we could easily create an index value type so we can store it and reuse it as we please so as to not violate the DRY principle.

But as we saw, we can still use the fromEnd variable to better project our intent that we wish for the last item and also retrieve the last item from an array with unknown size at compile time.

One thing that we need to remember though is that when counting from the end, we do not 0-index. Think of it as we were using Length-x where x is the value we would also use in the Index struct constructor.

But where does the hat operator fit in all of this?
Well the hat operator is a shorthand for a call to the Index struct with fromEnd set to true.
for example the two following lines are identical

Or if you wanted the second from last item you could do

So there it is, a new struct and a new usage for an old operator all packaged in one. C# 8 is bringing a huge bunch to the table and we cannot wait for it to be fully rolled out.

Please follow and like us:

Leave a Reply