How do I define an Extension Method for IEnumerable<T> which returns IEnumerable<T>? The goal is to make the Extension Method available for all IEnumerable and IEnumerable<T> where T can be an anonymous type.
How do I define an Extension Method for IEnumerable<T> which returns IEnumerable<T> ? The
Share
The easiest way to write any iterator is with an iterator block, for example:
The key here is the ‘
yield return‘, which turns the method into an iterator block, with the compiler generating an enumerator (IEnumerator<T>) that does the same. When called, generic type inference handles theTautomatically, so you just need:The above can be used with anonymous types just fine.
You can, of coure, specify the
Tif you want (as long as it isn’t anonymous):Re
IEnumerable(non-generic), well, the simplest approach is for the caller to use.Cast<T>(...)or.OfType<T>(...)to get anIEnumerable<T>first. You can pass inthis IEnumerablein the above, but the caller will have to specifyTthemselves, rather than having the compiler infer it. You can’t use this withTbeing an anonymous type, so the moral here is: don’t use the non-generic form ofIEnumerablewith anonymous types.There are some slightly more complex scenarios where the method signature is such that the compiler can’t identify the
T(and of course you can’t specify it for anonymous types). In those cases, it is usually possible to re-factor into a different signature that the compiler can use with inference (perhaps via a pass-thru method), but you’d need to post actual code to provide an answer here.(updated)
Following discussion, here’s a way to leverage
Cast<T>with anonymous types. The key is to provide an argument that can be used for the type inference (even if the argument is never used). For example: