C# yield operator
Prior to .NET 2.0, the only way you could create your own collection which could be traversed using the 'foreach' construct was by having you class implementing the IEnumerable and IEnumerator Interfaces.
However since .NET 2.0 we have a new operator called 'yield'. This allows your class to be iterated by its consumer but without the need to implement the above-mentioned interfaces.
Let us see a small example of how this works:
// Our class does not implement any interface ! public class School { // Explicit
initialization just for demo purposes ! private string[] studentNames = {"John",
"Joan","Joanne", "Tony", "Peter"};
// The iterating
method public
IEnumerator GetEnumerator() { foreach
(string name in
studentNames) { // yield
return in action ! yield
return name; } } } And now the code for the consumer:
class Program { static void Main(string[]
args) { School NorthCoast = new School(); // How
School's internal collection was iterated is hidden to the user foreach
(string student in
NorthCoast) {
(Continued...) View Full Aritlce
|