Not Rocket Science

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 Stack Overflow, and since I needed this so many times now, I've decided to write it.

Note that this requires the .net 3.5 Compiler.