Using yield to create an IEnumerator when C# with Example



Using yield to create an IEnumerator when C# with Example

implementing IEnumerable 
The IEnumerable interface has a single method, GetEnumerator(), which returns an IEnumerator. 
While the yield keyword can be used to directly create an IEnumerable, it can also be used in exactly the same 
way to create an IEnumerator. The only thing that changes is the return type of the method. 
This can be useful if we want to create our own class which implements IEnumerable: 
public class PrintingEnumerable : IEnumerable 
{ 
private IEnumerable _wrapped; 
public PrintingEnumerable(IEnumerable wrapped) 
{ 
_wrapped = wrapped; 
} 
// This method returns an IEnumerator, rather than an IEnumerable 
 

// But the yield syntax and usage is identical. 
public IEnumerator GetEnumerator() 
{ 
foreach(var item in _wrapped) 
{ 
Console.WriteLine("Yielding: " + item); 
yield return item; 
} 
} 
IEnumerator IEnumerable.GetEnumerator() 
{ 
return GetEnumerator(); 
} 
} 
(Note that this particular example is just illustrative, and could be more cleanly implemented with a single iterator 
method returning an IEnumerable.) 

0 Comment's

Comment Form