my Code is :
using System;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
namespace IEnumerable
{
public class MyEnumerable<T> : IEnumerable<T>
{
public MyEnumerable(T[] items)
{
this.items = items;
}
public IEnumerator<T> GetEnumerator()
{
return new NestedEnumerator(this);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
// The enumerator definition.
class NestedEnumerator : IEnumerator<T>
{
public NestedEnumerator(MyEnumerable<T> coll)
{
Monitor.Enter(coll.items.SyncRoot);
this.index = -1;
this.coll = coll;
}
public T Current
{
get { return current; }
}
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
if (++index >= coll.items.Length)
{
return false;
}
else
{
current = coll.items[index];
return true;
}
}
public void Reset()
{
current = default(T);
index = 0;
}
public void Dispose()
{
try
{
current = default(T);
index = coll.items.Length;
}
finally
{
Monitor.Exit(coll.items.SyncRoot);
}
}
private MyEnumerable<T> coll;
private T current;
private int index;
}
private T[] items;
}
public class EntryPoint
{
static void Main()
{
MyEnumerable<int> integers = new MyEnumerable<int>(new int[] { 1, 2, 3, 4 });
foreach (int n in integers)
{
Console.WriteLine(n);
}
}
}
}
I am implementing this piece of code But i get an error. Can anybody help me what to do to error free this code? please help.
My Errors are :
1->’IEnumerable’ is a ‘namespace’ but is used like a ‘type’
2->’IEnumerable.MyEnumerable’ does not implement interface member ‘System.Collections.IEnumerable.GetEnumerator()’. ‘IEnumerable.MyEnumerable.GetEnumerator()’ cannot implement ‘System.Collections.IEnumerable.GetEnumerator()’ because it does not have the matching return type of ‘System.Collections.IEnumerator’.
The error is likely that you’re using
IEnumerableas your namespace when it’s already a type in the system.This means that your references to
IEnumerableare refering to the current namespace and not theIEnumerableyou’re meaning to use (System.Collections.IEnumerable).Try changing your namespace to something else.