Is there a C# IN operator?

Tags: C#, In operator, .Net, In keyword

The short answer is “No”.

The long answer is you can achieve a similar result using extension methods:


/// <summary>
/// Array extention methods
/// </summary>
public static class ArrayExtensions
{
    /// <summary>
    /// the In extension method lets you write stuff like
    /// string item = "Bob";
    /// if (item.In("andy", "joel", "matt"))  { /* do stuff */}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="item"></param>
    /// <param name="items"></param>
    /// <returns></returns>
    public static bool In<T>(this T item, params T[] items)
    {
        if (items == null)
            return false;

        return items.Contains(item);
    }

    /// <summary>
    /// the In extension method lets you write stuff like
    /// string item = "Bob";
    /// if (item.NotIn("andy", "joel", "matt"))  { /* do stuff */}
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="item"></param>
    /// <param name="items"></param>
    /// <returns></returns>
    public static bool NotIn<T>(this T item, params T[] items)
    {
        if (items == null)
            return true;

        return !items.Contains(item);
    }
}

Sources:

No Comments

Add a Comment