How does the compiler use 'yield return' to build a class
c#
Solution
It builds a state machine, basically:
- It creates a private nested class, with instance variables corresponding to the local variables in your method, and a `state` variable to keep track of where it's got to
- The state machine implements `IEnumerable<T>` and `IEnumerator<T>` - the `MoveNext()` method gets to the right bit of the logic (based on `state`) and sets an instance variable to keep track of the last-yielded value (the `Current` property)
- The compiler creates a "skeleton" method with the same signature as your original, which creates an instance of the state machine
See my article on the topic for more details. Also note that async/await in C# 5 is built with a lot of the same ideas (although there are various implementation differences).
Problem
In specific, if I say: ``` public static IEnumerable<String> Data() { String connectionString = "..."; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); IDataReader reader = new SqlCommand("", connection).ExecuteReader(); while (reader.Read()) yield return String.Format("Have a beer {0} {1}!", reader["First_Name"], reader["Last_Name"]); connection.Close(); } } ``` How does the compiler go about generating a concrete enumerable class out of this?