Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloaded use of yield return

Tags:

yield

c#

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);
}
like image 514
bendewey Avatar asked Feb 09 '09 14:02

bendewey


2 Answers

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.

like image 109
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet


Yes, because yield return just generates an IEnumerator class on compile. yield return is just compiler magic.

like image 25
Nick Berardi Avatar answered Sep 28 '22 07:09

Nick Berardi