String Extensions – C#

Using built-in string methods can help us get the desired result but you repeat the code everywhere in need and I felt isolating the logic to one place will help the logic maintainable and testable. We can have all the below methods in a class file. (StringExtensions )

1.toDate

Accepts a string and convert as DateTime. It has an optional parameter throwExceptionIfFailed. if it is true then caller of this method should expect exception and handle it. Default is false which means that it returnsDateTime.MinValue if the string cannot be converted as DateTime

public static DateTime toDate(this string input, bool throwExceptionIfFailed = false)
{
    DateTime result;
    var valid = DateTime.TryParse(input, out result);
    if (!valid)
        if (throwExceptionIfFailed)
            throw new FormatException(string.Format("'{0}' cannot be converted as DateTime", input));
    return result;
}

2.toInt

public static int toInt(this string input, bool throwExceptionIfFailed = false)
{
    int result;
    var valid = int.TryParse(input, out result);
    if (!valid)
        if (throwExceptionIfFailed)
            throw new FormatException(string.Format("'{0}' cannot be converted as int", input));
    return result;
}

3.toDouble

public static double toDouble(this string input, bool throwExceptionIfFailed = false)
{
    double result;
    var valid = double.TryParse(input, NumberStyles.AllowDecimalPoint, 
      new NumberFormatInfo { NumberDecimalSeparator = "." }, out result);
    if (!valid)
        if (throwExceptionIfFailed)
            throw new FormatException(string.Format("'{0}' cannot be converted as double", input));
    return result;
}

4.reverse

public static string reverse(this string input)
{
    if (string.IsNullOrWhiteSpace(input)) return string.Empty;
    char[] chars = input.ToCharArray();
    Array.Reverse(chars);
    return new String(chars);
}

6.getLast

public static string getLast(this string input, int howMany)
{
    if (string.IsNullOrWhiteSpace(input)) return string.Empty;
    var value = input.Trim();
    return howMany >= value.Length ? value : value.Substring(value.Length - howMany);
}


7.getFirst

public static string getFirst(this string input, int howMany)
{
    if (string.IsNullOrWhiteSpace(input)) return string.Empty;
    var value = input.Trim();
    return howMany >= value.Length ? value : input.Substring(0, howMany);
}

8.isEmail

public static bool isEmail(this string input)
{
    var match = Regex.Match(input, 
      @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
    return match.Success;
}

9.isPhone

public static bool isPhone(this string input)
{
    var match = Regex.Match(input, 
      @"^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$", RegexOptions.IgnoreCase);
    return match.Success;
}

And the test methods

[TestMethod]
public void isPhone_ValidNumberPrefixedPlus_true()
{
    Assert.AreEqual(true, "+1234".isPhone());
}

10.isNumber

public static bool isNumber(this string input)
{
    var match = Regex.Match(input, @"^[0-9]+$", RegexOptions.IgnoreCase);
    return match.Success;
}  


Advertisements

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