This project is read-only.
1
Vote

Unintended boxing in "In<T>"

description

The two overloads of ObjectExtensions.In<T> call "item.Equals(t)", but as there is no IEquatable<T> constraint on the type parameter, this is equivalent to "((object)item).Equals((object)t)". If T is a value type, this will box every item in the sequence.
 
To avoid the boxing, you can either add a generic type constraint to the method (where T : IEquatable<T>), or use the EqualityComparer<T>.Default instance to check for equality.
 
Also, this method is a perfect case for the ".Any(predicate)" extension method.
 
public static bool In<T>(this T t, IEnumerable<T> enumerable)
{
if (null == enumerable) throw new ArgumentNullException("enumerable");
return enumerable.Any(item => EqualityComparer<T>.Default.Equals(item, t));
}
 
public static bool In<T>(this T t, params T[] items)
{
if (null == items) throw new ArgumentNullException("items");
return In(t, items.AsEnumerable());
}

comments