public interface IEnumerator // provide structure for traversal in collection.
{
bool MoveNext();
object Current { get; }
void Reset();
}
public interface IEnumerable // access the IEnumerator instant for travelsal operation.
{
IEnumerator GetEnumerator();
}
question is that why we used two different interface for traversal in collection.
IEnumerable provides flexibility in the iteration logic can be farmed off to another class. Moreover, it means that several consumers can enumerate the collection at once without interfering with each other.
Take example: IEnumerator is like a book. IEnumerable is like a reader. You can have many readers reading the same book, and each of them on a different page.
Two main Difference :
1. IEnumerable is Sugar-coated internally to IEnumerator . But IEnumerable has easy syntax compare to
IEnumerator for iteration of list.
IEnumerable<int> ie = (IEnumerable<int>)ls;
foreach (var item in ie) //IEnumerable used the foreach syntax and it is easy to write.
{
Console.WriteLine(item);
}
if you use IEnumerator then
IEnumerator<int> iet = ls.GetEnumerator();
while (iet.MoveNext()) // manually do the iteration
{
Console.WriteLine(iet.Current);
}
2. IEnurator preserve state of Object which are using for iteration. But IEnumerable is not preserve state of Object(means if you are inside of foreach statement and you called other function then the state of object which are currently display are not presrve in calling function).
For More Click Here
{
bool MoveNext();
object Current { get; }
void Reset();
}
public interface IEnumerable // access the IEnumerator instant for travelsal operation.
{
IEnumerator GetEnumerator();
}
question is that why we used two different interface for traversal in collection.
IEnumerable provides flexibility in the iteration logic can be farmed off to another class. Moreover, it means that several consumers can enumerate the collection at once without interfering with each other.
Take example: IEnumerator is like a book. IEnumerable is like a reader. You can have many readers reading the same book, and each of them on a different page.
Two main Difference :
1. IEnumerable is Sugar-coated internally to IEnumerator . But IEnumerable has easy syntax compare to
IEnumerator for iteration of list.
IEnumerable<int> ie = (IEnumerable<int>)ls;
foreach (var item in ie) //IEnumerable used the foreach syntax and it is easy to write.
{
Console.WriteLine(item);
}
if you use IEnumerator then
IEnumerator<int> iet = ls.GetEnumerator();
while (iet.MoveNext()) // manually do the iteration
{
Console.WriteLine(iet.Current);
}
2. IEnurator preserve state of Object which are using for iteration. But IEnumerable is not preserve state of Object(means if you are inside of foreach statement and you called other function then the state of object which are currently display are not presrve in calling function).
For More Click Here
No comments:
Post a Comment