c# - Creating an extension method to wrap types as IEnumerables -
i wanted create extension method efficiently wrap single objects ienumerables. avoid cases end putting new [] {} in middle of expression. easy enough using following method:
public static ienumerable<tsource> wrapasenumerable<tsource>(this tsource source) { return new[] { source }; } the problem applied , types (which expected behavior), have side effect of making method available on ienumerable <t> instances. in case resolved extended type ienumerable<t>, return ienumerable, since aternative finding myself ienumerable<ienumerable<t>>, not you'd expect when calling method.
instinctively (and perhaps sleepily), first created overload looked this
public static ienumerable<tsource> wrapasenumerable<tsource>(this ienumerable<tsource> source) { return source; } in order handle case type wrap ienumerable<t>, of course, control flow resolves first method.
so, question is: how create such wrapping method handles both case extended parameter instance ienumerable<t> , when not ?
here attempt, inspired eric lippert's excellent post at: https://stackoverflow.com/a/1451184/4955425.
you can control overloading resolution placing 2 extension methods @ different levels in namespace hierarchy.
namespace myextensions { public static class highprecendenceextensions { public static ienumerable<tsource> wrapasenumerable<tsource>(this ienumerable<tsource> source) { return source; } } namespace lowerprecedencenamespace { public static class lowprecedenceextensions { public static ienumerable<tsource> wrapasenumerable<tsource>(this tsource source) { return new[] { source }; } } } } however, downside you'll need refer both namespaces right method invocation behavior.
using myextensions; using myextensions.lowerprecedencenamespace;
Comments
Post a Comment