A Safe String.SubString Extension Method

The String.Substring method in .net is useful, but has one slight quirk: If you try to read too much (i.e. "123".Substring(1,5)), you get an ArgumentOutOfRangeException saying that "Index and length must refer to a location within the string.". Here is an extension method that will not throw an exception, but instead return a truncated string, even it it is shorter than desired. That way, you can use it as a way to always Truncate longer strings while leaving shorter ones unchanged.

public static class StringExtensions
{
    public static string SafeSubstring(this string input, int startIndex, int length)
    {
        // Todo: Check that startIndex + length does not cause an arithmetic overflow
        if (input.Length >= (startIndex + length))
        {
            return input.Substring(startIndex, length);
        }
        else
        {
            if (input.Length > startIndex)
            {
                return input.Substring(startIndex);
            }
            else
            {
                return string.Empty;
            }
        }
    }
}

This was inspired by a Question on StackOverflow, and since I needed this so many times now, I've decided to write it.

Note that this requires the .net 3.5 Compiler.

Comments (5)

software developersAugust 11th, 2009 at 18:38

Cool,

split can be used in this example as well

Thanks

Andrei RineaOctober 3rd, 2009 at 22:55

A small correction : the .NET 3.5 compiler

mstumOctober 4th, 2009 at 15:03

Indeed. It's the C# 3.0 Compiler included in .net 3.5. Confusing Version numbers 🙂

Andrei RineaOctober 5th, 2009 at 15:17

Got bitten by these confusing numbers myself too. Ah well, these confusions will end in 4.0 🙂

AaronNovember 13th, 2012 at 19:01

Good simple technique to solve this common problem. I did the same but a slight modification to reduce the lines of code and make it a little cleaner.

public static string SafeSubstring(this string source, int startIndex, int length)
{
if (startIndex > source.Length-1)
{
throw new ArgumentException("Start index cannot be greater than string length.", "startIndex");
}

return startIndex + length > source.Length ? source.Substring(startIndex) : source.Substring(startIndex, length);
}