Navigate to Post

Monday, April 13, 2020

Learn C#~#6 Index from the end operator ^


^ specifies the index from the end of a sequence. It simplifies the calculation required to get the correct index from the start of the array. Now, you can directly specify the index from the end, which is easier to understand and shorter.

e.g., Get the second last item of an array


PROGRAM



using System;

namespace MyTestConsole
{
    class Program
    {
        static void Main()
        {
            var array = new[] { 1, 2, 3, 4, 5, 23, 45, 56, 78, 89 };

            // Before
            var x = array[array.Length - 2]; // 4
            Console.WriteLine($"[BEFORE] Second last item is {x}");

            // Now this is also allowed
            var y = array[^2]; // 4
            Console.WriteLine($"[AFTER] Second last item is {y}");

            Console.ReadKey();
        }
    }
}


OUTPUT





All time trending post