Friday, May 15, 2009

C# Generic Extension Methods

Just found this interesting generic extension method "Is<T>" on hardcodet.net.

/// <summary>
/// Checks a list of candidates for equality to a given
/// reference value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The evaluated value.</param>
/// <param name="candidates">A list of possible values that are
/// regarded valid.</param>
/// <returns>True if one of the submitted <paramref name="candidates"/>
/// matches the evaluated value. If the <paramref name="candidates"/>
/// parameter itself is null, too, the method returns false as well,
/// which allows to check with null values, too.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="candidates"/>
/// is a null reference.</exception>
public static bool Is<T>(this T value, params T[] candidates)
{
if (candidates == null) return false;

foreach (var t in candidates)
{
if (value.Equals(t)) return true;
}

return false;
}


So you can do stuff like this:

string status = Order.StatusCode;
if(status.Is("UnAssigned","Cancelled","Suspended"))
{
//Do Something
}

No comments:

Post a Comment