Hi, Nicholas,
Thank you for your reply. The follwoing is my source code.
In the source code, I implemented 3 iterators. The first implements
IEnumerable.GetEnumerator method. The second implements a named iterator
MyCollection.BuildMyCollection. The third implements an iterator in a
property.
In the first 2 iterators, I tried to use 'yield break' and 'break'
respectively. They seems to have the same effect.
using System;
using System.Collections.Generic;
using System.Text;
namespace TestIterator
{
class Program
{
static void Main(string[] args)
{
TestIterator();
}
private static void TestIterator()
{
MyCollection col = new MyCollection();
// Display the collection items:
Console.WriteLine("Values in the collection are:");
// Use iterator 1.
foreach (int i in col)
{
Console.WriteLine(i);
}
// Use iterator 2.
foreach (int i in col.BuildMyCollection())
{
Console.WriteLine(i);
}
// Use property iterator
foreach (int i in col.AllItems)
{
Console.WriteLine(i);
}
}
}
// Declare the collection:
public class MyCollection
{
public int[] items;
// Implement an iterator as a property.
// It can only be the named iterator.
public IEnumerable<int> AllItems
{
get
{
foreach (int i in items)
{
yield return i;
}
}
}
public MyCollection()
{
items = new int[5] { 5, 4, 7, 9, 3 };
}
// Iterator 1: Implement IEnumerable<T>.GetEnumerator method
// or IEnumerable.GetEnumerator method.
public IEnumerator<int> GetEnumerator()
{
for (int i = 0; i < items.Length; i++)
{
if (i >= 2)
{
//yield break;
break;
}
yield return items[i];
}
}
// Iterator 2: Named method
// Implement a method which returns IEnumerable<T> or IEnumberable.
public IEnumerable<int> BuildMyCollection()
{
for (int i = 0; i < items.Length; i++)
{
if (i >= 2)
{
//yield break;
break;
}
yield return items[i];
}
}
}
}
"Nicholas Paldino [.NET/C# MVP]" wrote:
Can you show your code?
Chances are that your break statement is producing the end of the
production at the same time (and therefore, returning nothing).
Without seeing your code, it's hard to say though.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com
"yyhhjj" <yy****@discussions.microsoft.com> wrote in message
news:FA**********************************@microsof t.com...I created a test program to implement an iterator.
First, I used 'yield break' in the iterator, it worked normally.
Then, I simply used 'break' in the places of 'yield break', it still
worked
normally.
What's the difference between 'yield break' and 'break' here?
Thanks!