Wednesday, May 27, 2009

Yield Passes Control Through Intermediate Calls

I was wanting to be able to perform a backend database service in a batch mode, but wanted to make the actual batch processing part of it as encapsulated as possible.

I created a BO that returned an IEnumerable<List<MyBO>>, but it didn't use any yield statements, it just called a data access layer that was using the yield statements. I was concerned if this was going to work, so I decided to test it using snippet compiler.

So this is my quick and dirty test to see if it would work:

public static void RunSnippet()
{
foreach (List<string> answers in GetAnswers())
{
WL(answers.Count);
foreach (string answer in answers)
{
WL(answer);
}
}
}

public static IEnumerable<List<string>> GetAnswers()
{
return GetTheAnswers();
}

private static IEnumerable<List<string>> GetTheAnswers()
{
List<string> answers = new List<string>();
answers.Add("A");
answers.Add("B");
answers.Add("C");
answers.Add("D");
yield return answers;

answers = new List<string>();
answers.Add("D");
answers.Add("C");
answers.Add("B");
answers.Add("A");
yield return answers;

answers = new List<string>();
answers.Add("X");
answers.Add("Y");
answers.Add("Z");
yield return answers;
}






And these were the results:
4
A
B
C
D
4
D
C
B
A
3
X
Y
Z


So even though GetAnswers() gets called once, GetTheAnswers() will return control back to the enumerating foreach multiple times.

No comments: