Tuesday 8 September 2009

IsIn Extension Method

Another useful extension method I've found is the IsIn() method. This is comes in handy when you have to test for enumeration values, for example:
public enum StatusValues
{
 Open,
 Closed,
 Pending,
 Cancelled,
 Expired,
 Suspended
}

   ...

if(myObject.Status == StatusValues.Closed ||
   myObject.Status == StatusValues.Pending ||
   myObject.Status == StatusValues.Expired)
{  
   ...
}

This can become cumbersome when testing for a number of values.

The IsIn Extension Method simplifies this by taking a param list of values.
public static bool IsIn<T>(this T thisObject, params T[] values)
{
    if (thisObject != null && values != null && values.Length > 0)
    {
        foreach (var value in values)
        {
            if (thisObject.Equals(value))
            {
                return true;
            }
        }
    }

    return false;
}
Using this method, the above code can be rewritten as follows:

//using the IsIn Extension Method
if(myObject.Status.IsIn(StatusValues.Closed,
                        StatusValues.Pending,
                        StatusValues.Expired))
{
   ...
}

No comments: