Sunday, August 04, 2024

C# From-The-End Index Operator ^ C# 13

Implicit index access

With C# 13, the implicit “From-The End” index operator ^ can now be used in object initializers. You can use ^ to specify a position in a collection that is relative to the end of the collection.

For example, consider the following class.

class InitializerDemo
{
    public int[] integers { get; set; } = new int[5];
}

You can now use the following piece of code in C# 13 to take advantage of the index operator.

var arr = new InitializerDemo
{
    integers =
    {
        [0] = 100,
        [^1] = 1000
    }
};

When you execute the above program, arr.Integers[0] will have the value 100 while arr.Integers[4] will have the value 1000. 

No comments:

Thumbs Up to GitHub Copilot and JetBrains Resharper

Having used AI tool GitHub Copilot since 08/16/2023, I’ve realized that learning GitHub Copilot is like learning a new framework or library ...