Does anyone knonw if you can add the IEnumerator to a struct or just a
class. If you can add it to a struct, can you please show me a valid,
simple example?
Marc Gravell - 10 Mar 2008 17:10 GMT
Should be fine (see below). Was there a specific issue you were
seeing?
Marc
using System;
using System.Collections;
using System.Collections.Generic;
struct MyTuple : IEnumerable<int>
{
public readonly int a, b, c, d, e; // lazy... should be props
public MyTuple(int a, int b, int c, int d, int e)
{
this.a = a; this.b = b; this.c = c;
this.d = d; this.e = e;
}
public IEnumerator<int> GetEnumerator()
{
yield return a;
yield return b;
yield return c;
yield return d;
yield return e;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
static class Program
{
static void Main()
{
MyTuple tuple = new MyTuple(1, 2, 3, 4, 5);
foreach(int x in tuple) {
Console.WriteLine(x);
}
}
}
pipo - 10 Mar 2008 17:10 GMT
public struct StructTest : IEnumerator
{
#region IEnumerator Members
public object Current
{
get { throw new Exception("The method or operation is not implemented."); }
}
public bool MoveNext()
{
throw new Exception("The method or operation is not implemented.");
}
public void Reset()
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
For a class it is the same but then public class instead of public struct
> Does anyone knonw if you can add the IEnumerator to a struct or just a
> class. If you can add it to a struct, can you please show me a valid,
> simple example?
Marc Gravell - 10 Mar 2008 17:13 GMT
Ah, sorry, I misread IEnumerator as IEnumerable.
Yes it is perfectly possible, but be careful; this type of usage often
means making the struct mutable (otherwise what would MoveNext do...)
- which can cause problems if used in certain ways... but the core MS
libs use struct enumerators in a number of places -
List<T>.Enumerator, for example.
Personally I wouldn't recommend writing your own enumerator; in C# 2
and above the yield syntax does it for you...
Marc