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 ?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With