C#|.NET : Safe Substring

substring
Substring is a very handy function when you want to do something with part of a given string. The problem with Substring is that if you do not do proper range checking, it will throw ArgumentOutOfRangeException. Check these statement:

string _s = "123456";
string _x = _s.Substring(2,6);
string _x = _s.Substring(7,2);

Line 2 and Line 3 will throw error – ArgumentOutOfRangeException

Here comes a one-line safe substring extension method:

namespace YourCompanysAwesomeExtensions
{
        public static string SafeSubstring(this string value, int startIndex, int length)
        {
            return new string((value ?? string.Empty).Skip(startIndex).Take(length).ToArray());
        }
}

Use SafeSubstring as Substring:

string _s = "123456";
string _x = _s.SafeSubstring(2,6); //returns "3456"
string _x = _s.SafeSubstring(7,2); //returns ""

I am not saying you should not check the range of your arguments. You should. This is for those cases where you want substring to return a string, whatever values you get at run-time. This method fulfills following requirements:

  • returns empty string if start-index is out of range
  • returns string from start to given length, if start-index is smaller than 0
  • returns string from start-index to end of string, if length argument is beyond number of characters left
  • returns appropriate string if arguments in valid range

Happy coding!

Advertisements

8 thoughts on “C#|.NET : Safe Substring

  1. Pingback: C# | .NET Extension Methods | Sharp Statements

  2. I am working on a parsing project and was looking at the performance of Safe Substring methods.

    public static class Extensions
    {
    public static string SafeSubstring(this string value, int startIndex, int length)
    {
    if (!string.IsNullOrWhiteSpace(value))
    {
    if (value.Length >= (startIndex + length))
    {
    return value.Substring(startIndex, length);
    }
    else if (value.Length >= startIndex)
    {
    return value.Substring(startIndex);
    }
    }
    return string.Empty;
    }
    }

    Elapsed = {00:00:00.0001419}

    public static class Extensions
    {
    public static string SafeSubstring(this string value, int startIndex, int length)
    {
    return new string((value ?? string.Empty).Skip(startIndex).Take(length).ToArray());
    }
    }

    Elapsed = {00:00:00.0036977}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s