How yield implements the pattern of lazy loading?
How yield implements the pattern of lazy loading ?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
yield implementation doesn’t reach the code until it’s needed.
For example, this code:
Will actually compile into a nested class which implements
IEnumerable<int>and the body ofGetInts()will return an instance of that class.Using reflector you can see:
Edit – adding more info about
GetIntsimplementation:The way this implementation makes it lazy is based on the
EnumeratorMoveNext()method. When the enumerable nested class is generated (<GetInts>d__6din the example), it has a state and to each state a value is connected (this is a simple case, in more advanced cases the value will be evaluated when the code reach the state). If we take a look in theMoveNext()code of<GetInts>d__6dwe’ll see the state:When the enumerator is asked for the current object it returns the object which is connected to the current state.
In order to show that the code is evaluated only when it’s required you can look at this example:
I hope it’s a bit more clear. I recommend to take a look at the code with Reflector and observe the compiled code as you change the “yield” code.