Description This article explains how to implement enumerators in C#.We know how to use foreach for built-in types of C#.But how do we Use for objects of our class. For class Employee { } how do we use foreach for the objects of Employee. Step#1:
To foreach construct for user-defined classes the first thing we have to do is Imlplement the interface IEnumerable. Then Ienumerable interface has a method called GetEnumerator() which returns an object of IEnumerator.
Step#2:
Next we have to implement IEnumerator interface.The IEnumerator has 3 methods namely Reset(),Current(),MoveNext().After we code for the 3 methods we are able to use foreach() for our UDC(User Defined Classes).
Step#3:
How does foreach works when we use foreach() construct it first Calls MoveNext() if it returns true then the loop is continued to the value from the Current() method call.Reset() is used to set the Enumerator to begining position.
Let's run through a coding sample which will make things clear: The source code has 2 classes namely Employee,Employees. Employee class hold information about each Employee. The Employees class hold array of Employee objects.
Source Code Explanation:
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: