I don't have much experience with using the yield keyword. I have these IEnumerable<T> extensions for Type Conversion.
My question is does the first overloaded method have the same yield return effect that I'm getting from the second method?
public static IEnumerable<TTo> ConvertFrom<TTo, TFrom>(this IEnumerable<TFrom> toList)
{
return ConvertFrom<TTo, TFrom>(toList, TypeDescriptor.GetConverter(typeof(TTo)));
}
public static IEnumerable<TTo> ConvertFrom<TTo, TFrom>(this IEnumerable<TFrom> toList, TypeConverter converter)
{
foreach (var t in toList)
yield return (TTo)converter.ConvertFrom(t);
}
When you call the first overload, it will immediately call the second overload. That won't execute any of the code in its body, which will have been moved into a nested class implementing the iterator block. When GetEnumerator()
and then MoveNext()
are first called on the returned IEnumerable<TTo>
, then the code in your second overload will begin executing.
I have a fairly long article on the iterator block implementation, which you may find interesting.
Yes, because yield return just generates an IEnumerator class on compile. yield return
is just compiler magic.
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