It's been a while since i wrote the last post, but i did not forget my purpose of creating a series that shows the evolution of C#. Today i came here to talk about one of the most useful features of C#, even if you dont know you're using it. Let's talk about iterators!
What is an iterator?
For those of you who didn't read about the iterator pattern somewhere in the internet or in the "Gang of Four" book, you can read a description here. The iterator is a class/object/whatever which knows how to traverse a structure. So, if you have a list or collection of objects, an iterator would have the knowledge of how to traverse that collection and access each element that it contains. The iterator is a well known design pattern and is behind many of the wonderful that we have nowadays in .NET (Linq comes to mind).
Why is it a feature?
Truth be told, an iterator is a concept well known way before .NET even existed. Being an OO Design Pattern, the iterator has been used everywhere. The iterator object typically has some methods by convention. To implement the iterator pattern in .NET 1.0 you needed to implement the IEnumerator interface. Then, in the class that needs to be traversed, you implement the IEnumerable interface which has a method that returns an instance of the enumerator. It's easier if we look at this example:
In the example above we can see that the Box class implements IEnumerable and it's GetEnumerator method returns a new instance of the BoxItemEnumerator. BoxItemEnumerator implements the IEnumerator interface and receives the items in the constructor. This is the class that knows how to traverse the items in the box, and this way we can return as many iterators as we want through the GetEnumerator method. Also, this will allow us to do this:
Notice how we can use the Box instance in the foreach. Behind the scenes, the framework will call the MoveNext method and Current property of the BoxItemEnumerator instance in each iteration, convert it to string and put it in the item variable. This will of course print the names of the items.
So, where is the real improvement? We had this already!
The answer lies in the yield keyword. Now we can build an iterator without having to implement the IEnumerator class! Check the code below:
The above snippet does exactly the same thing as the first, but notice how i didn't have to implement the IEnumerator interface to get the same result! This is a massive time saver if you had to implement all that plumbing code! But what does that yield do? Notice that each time the GetEnumerator method is executed, yield will save the state of the execution and will resume the method from there. You can try it out with the debugger and see that the method never really exits until the end of the foreach loop on the items, it just pauses. You can implement as many iterators as you want and then refer to them in client code by calling the method in the foreach loop.
To get out of the loop, you can use yield break in the GetEnumerator method and the loop will obviously end. You can also use an iterator in a get acessor of a property and have the same results. Note that the return type of an iterator method must be IEnumerable, IEnumerator, IEnumerable(of T) or IEnumerator(of T).
Whenever you think it will help you, use an iterator. I never really needed to implement an iterator, because most of the structures that i use already implement IEnumerable, but never say never!
Next time in Run or Debug we will take a look at yet another feature of .NET 2.0: Partial classes.
What is an iterator?
For those of you who didn't read about the iterator pattern somewhere in the internet or in the "Gang of Four" book, you can read a description here. The iterator is a class/object/whatever which knows how to traverse a structure. So, if you have a list or collection of objects, an iterator would have the knowledge of how to traverse that collection and access each element that it contains. The iterator is a well known design pattern and is behind many of the wonderful that we have nowadays in .NET (Linq comes to mind).
Why is it a feature?
Truth be told, an iterator is a concept well known way before .NET even existed. Being an OO Design Pattern, the iterator has been used everywhere. The iterator object typically has some methods by convention. To implement the iterator pattern in .NET 1.0 you needed to implement the IEnumerator interface. Then, in the class that needs to be traversed, you implement the IEnumerable interface which has a method that returns an instance of the enumerator. It's easier if we look at this example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Box : IEnumerable | |
{ | |
string[] itemNames; | |
public Box() | |
{ | |
itemNames = new string[5]; | |
itemNames[0] = "Clothes"; | |
itemNames[1] = "Spoons"; | |
itemNames[2] = "Toys"; | |
itemNames[3] = "Tools"; | |
itemNames[4] = "Plates"; | |
} | |
public IEnumerator GetEnumerator() | |
{ | |
return new BoxItemIterator(itemNames); | |
} | |
} | |
public class BoxItemIterator : IEnumerator | |
{ | |
int CurrentPosition = -1; | |
string[] itemNames = null; | |
public BoxItemIterator(string[] ItemNames) | |
{ | |
itemNames = ItemNames; | |
} | |
public bool MoveNext() | |
{ | |
CurrentPosition++; | |
return (CurrentPosition < itemNames.Length); | |
} | |
public void Reset() | |
{ | |
CurrentPosition = -1; //Sets the current position at the start of the collection | |
} | |
public object Current | |
{ | |
get | |
{ | |
return itemNames[CurrentPosition]; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Box b = new Box(); | |
foreach (string item in b) | |
{ | |
Console.WriteLine(item); | |
} |
So, where is the real improvement? We had this already!
The answer lies in the yield keyword. Now we can build an iterator without having to implement the IEnumerator class! Check the code below:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
Box b = new Box(); | |
foreach (string item in b) | |
{ | |
Console.WriteLine(item); | |
} | |
} | |
public class Box : IEnumerable | |
{ | |
string[] itemNames; | |
public Box() | |
{ | |
itemNames = new string[5]; | |
itemNames[0] = "Clothes"; | |
itemNames[1] = "Spoons"; | |
itemNames[2] = "Toys"; | |
itemNames[3] = "Tools"; | |
itemNames[4] = "Plates"; | |
} | |
public IEnumerator GetEnumerator() | |
{ | |
foreach (string item in itemNames) | |
yield return item; | |
} | |
} |
To get out of the loop, you can use yield break in the GetEnumerator method and the loop will obviously end. You can also use an iterator in a get acessor of a property and have the same results. Note that the return type of an iterator method must be IEnumerable, IEnumerator, IEnumerable(of T) or IEnumerator(of T).
Whenever you think it will help you, use an iterator. I never really needed to implement an iterator, because most of the structures that i use already implement IEnumerable, but never say never!
Next time in Run or Debug we will take a look at yet another feature of .NET 2.0: Partial classes.
Comments
Post a Comment