This code(C# 2.0) doesn't compile. But why?



using System;
using System.Collections.Generic;
using System.Text;

namespace Z
{
publicclass St<T> : IEnumerable<T>
{
T[] items;

int count;

publicvoid Push(T data) { T[count] = data; count++; }

public T Pop() { }

public IEnumerator<T> GetEnumerator()
{

for (int i = count - 1; i >= 0; --i)

yieldreturn items[i ];

}
}

class Program
{

staticvoid Main()
{

St<int> s =new St<int>();

for (int i = 0; i < 10; i++) s.Push(i);

foreach (int iin s) Console.Write("{0}", i);

}
}
}

I am working with C# Express Beta 2. Try to compile and get an error:
Error 1 'Z.St<T>' does not implement interface member 'System.Collections.IEnumerable.GetEnumerator()'. 'Z.St<T>.GetEnumerator()' is either static, not public, or has the wrong return type. C:\Documents and Settings\LocalService\Local Settings\Application Data\Temporary Projects\ConsoleApplication1\Program.cs 7 18 IteratorsExample

But Z.St<T>.GetEnumerator() NOT static, IS public and has return type IEnumerator<T> ! Where I did wrong?

[2119 byte] By [Smarty] at [2007-12-16]
# 1

That's because IEnumerable<T> is derived from the non-generic IEnumerable, so you need to satisfy its contract:


public class St<T> : IEnumerable<T>
{

T[] items;

int count;

public void Push(T data) { items[count] = data; count++; }

public T Pop() {

return default(T);
}

public IEnumerator<T> GetEnumerator()
{

for (int i = count - 1; i >= 0; --i)

yield return items[i ];
}

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}


DavidM.Kean at 2007-8-21 > top of Msdn Tech,Visual C#,Visual C# General...
# 2
You are absolutely right, thanks!
Smarty at 2007-8-21 > top of Msdn Tech,Visual C#,Visual C# General...