Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How can I make an extension accept IEnumerable instead of array for params

Tags:

c#

Having this extension

    public static bool In<T>(this T t, params T[] values)
    {
        return values.Contains(t);
    }

wanted it to accept IEnumerable and casting to array if needed inside the extension, but I don't know how to use the params keyword for that.

Tryed :

    public static bool In<T>(this T t, params IEnumerable<T> values)
    {
        return values.Contains(t);
    }

but this generates a compile-time error : The parameter array must be a single dimensional array

Is there any way to make the extension method support IEnumerable params ? if not, why not ?

like image 983
Bart Calixto Avatar asked Mar 04 '14 17:03

Bart Calixto


1 Answers

No, it's not possible, as the error message very bluntly tells you.

It's not possible because the specs say it's not possible. Microsoft has chosen to not implement the proposed feature, presumably because they never considered its benefits to be greater than its costs.

The best workaround you can manage is to create two overloads, one with params, and one accepting an IEnumerable<T>, and have one call the other (or, since your methods are so simple, just implement both):

public static bool In<T>(this T t, params T[] values)
{
    return In<T>(t, values.AsEnumerable());
}

public static bool In<T>(this T t, IEnumerable<T> values)
{
    return values.Contains(t);
}
like image 170
Servy Avatar answered Sep 30 '22 00:09

Servy