CSharpYield

October 01, 2008
using System.Collections;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;

[TestClass]
public class YieldReturnTest
{
private string sideEffect;

// just experiments to better understand yield return
[TestMethod]
public void TestYieldReturnIfCallerDoesNotIterate()
{
sideEffect = "";
YieldStrings();
/*
* Unfortunately, the yield method is not called
* at all if the caller is not going to iterate
* over it.
*/
Assert.AreEqual("", sideEffect);
}

protected IEnumerator YieldStrings()
{
sideEffect = "foo";
foreach (string s in new string[] {"a", "b", "c"})
{
yield return s;
}
}
}

[TestClass]
public class YieldReturnTest2
{
private string sideEffect;

// just experiments to better understand yield return
[TestMethod]
public void TestEnumeratorReturnWorksEvenIfCallerDoesNotIterate()
{
sideEffect = "";
YieldStrings();
Assert.AreEqual("foo", sideEffect);
}

protected IEnumerator YieldStrings()
{
sideEffect = "foo";
return new string[] {"a", "b", "c"}.GetEnumerator();
}
}

[TestClass]
public class TestYieldBreak
{
[TestMethod]
public void NormalBreak()
{
List strings = new List();
foreach (string s in YieldStringsWithNormalBreak())
{
strings.Add(s);
}
Assert.AreEqual(2, strings.Count);
}

[TestMethod]
public void YieldBreak()
{
List strings = new List();
foreach (string s in YieldStringsWithYieldBreak())
{
strings.Add(s);
}
// no difference?
Assert.AreEqual(2, strings.Count);
}

protected IEnumerable YieldStringsWithNormalBreak() {
int i = 0;
foreach (string s in new string[] {"a", "b", "c"})
{
yield return s;
i++;
if (i > 1) break;
}
}

protected IEnumerable YieldStringsWithYieldBreak() {
int i = 0;
foreach (string s in new string[] {"a", "b", "c"})
{
yield return s;
i++;
if (i > 1) yield break;
}
}
}

tags: ComputersAndTechnology
comments powered by Disqus