Two nice string extensions

Here’s a couple (well, one is an overload of the other) of string extension methods I wrote today which I’m quite fond of:


/// <summary>
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// </summary>
/// <param name="text">The string value to be checked</param>
/// <param name="matches">The list of potential matches</param>
static public bool IsIn(this string text, params string[] matches)
{
    return IsIn(text, true, matches);
}

/// <summary>
/// Determines if any of the given matches are a case sensitive match for the
/// nominated string value
/// </summary>
/// <param name="text">The string value to be checked</param>
/// <param name="caseSensitive"><c>true</c> to perform a case
/// sensitive match</param>
/// <param name="matches">The list of potential matches</param>
static public bool IsIn(this string text, bool caseSensitive, params string[] matches)
{
    StringComparison comparer = caseSensitive
        ? StringComparison.CurrentCulture
        : StringComparison.CurrentCultureIgnoreCase;

    return matches.Any(value => text.Equals(value, comparer));
}


So instead of writing this:


if (name == "James" || name == "Peter" || name == "Sally")
    Console.WriteLine("Your name is too generic!");

You can simply write this:


if (name.IsIn("James", "Peter", "Sally")
    Console.WriteLine("Your name is too generic!");

No offence to the James, Peters, and Sallys of the world.

Posted in .Net, C# by Gerrod at July 9th, 2009.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Quickduck logo