I wanted to create an extension method that would efficiently wrap single objects as IEnumerables. This was to avoid the cases where you end up putting a new [] {} in the middle of an expression. This is easy enough to do using the following method:
public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this TSource source)
{
return new[] { source };
}
The problem is that this will be applied to any and all types (which is the expected behavior), but this will also have the side effect of making the method available on IEnumerable <T> instances. In the case where the resolved extended type is an IEnumerable<T>, I would simply like to return this IEnumerable, since the aternative is finding myself with a IEnumerable<IEnumerable<T>>, which is not really what you'd expect when calling the method.
Instinctively (and perhaps sleepily), I first created an overload that looked like this
public static IEnumerable<TSource> WrapAsEnumerable<TSource>(this IEnumerable<TSource> source)
{
return source;
}
in order to handle the case where the type to wrap is an IEnumerable<T>, But of course, the control flow always resolves to the first method.
So, the question is: how could I create such a wrapping method that handles both the case where the extended parameter instance is an IEnumerable<T> and when it is not ?