Friday, July 10, 2020

SubstringOrDefault: a String Extension Method

Some time ago, I had a need for a String.Substring method in C# that could handle the case where the substring being requested started after the length of the string, or where the substring length was going to exceed the remaining length of the string.

I wanted it to fail gracefully: return an empty string in the first case, and in the second case, return as long a substring as it could. (The default Substring method will throw an exception in both cases.)

In the spirit of LINQ methods like SingleOrDefault(), which return Null if there is no data to return, I offer the following extension methods:

namespace System
{
    public static class ExtensionMethods
    {
        public static string SubstringOrDefault(this string s, int start, int length)
        {
            if (s == null)
                return null;
            if (start < 0)
                return string.Empty;
            if (length == 0)
                return string.Empty;
            if (start > s.Length)
                return string.Empty;
            if (length == -1)
                return s.Substring(start);
            if (start + length > s.Length)
                return s.Substring(start);
            return s.Substring(start, length);
        }
        public static string SubstringOrDefault(this string s, int start)
        {
            return SubstringOrDefault(s, start, -1);
        }
        public static string LeftOrDefault(this string s, int length)
        {
            return SubstringOrDefault(s, 0, length);
        }
        public static string RightOrDefault(this string s, int length)
        {
            if (s == null)
                return null;
            if (length > s.Length)
                return s;
            return SubstringOrDefault(s, s.Length - length, length);
        }
    }
}
Careful readers will note that I threw in two helper methods as well: LeftOrDefault and RightOrDefault. I've always been a little surprised there were no Left or Right methods on String.


Labels: