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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

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