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

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs