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

Neon image

Build better on Postgres with AI-Assisted Development Practices

Compare top AI coding tools like Cursor and Windsurf with Neon's database integration. Generate synthetic data and manage databases with natural language.

Read more →

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

👋 Kindness is contagious

If you found this post useful, please drop a ❤️ or leave a kind comment!

Okay