DEV Community

Cover image for Snippets in C#: Offsets and substrings
Matt Kenefick
Matt Kenefick

Posted on

Snippets in C#: Offsets and substrings

Today we have two fun snippets for C#. The first is a less verbose syntax for retrieving elements from the end of a list. The second is a similar syntax for substrings.

Retrieve an offset from the end

using System;

public class Program
{
    public static void Main()
    {
        int[] numbers = new int[] { 0, 1, 2, 3, 4, 5, 6 };

        // Equivalent to: 
        //    numbers[numbers.Length - 2].ToString()
        string number = numbers[^2].ToString();

        // Outputs: "Hello: 5"
        Console.WriteLine("Hello: " + number);
    }
}
Enter fullscreen mode Exit fullscreen mode

Retrieve a substring

using System;

public class Program
{
    public static void Main()
    {
        string sentence = "Roger is a good boy.";

        // Equivalent to: 
        //    sentence.Substring(9, sentence.Length - 9 - 1)
        string descriptionOfRoger = sentence[9..^1];

        // Outputs: "What is Roger? a good boy"
        Console.WriteLine("What is Roger? " + descriptionOfRoger);
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)