IEnumerable Interface in Visual Basic .NET

To understand the IEnumerable interface in VB.NET, I will create Student class and Course class. Since course has students I can use For...Each loop to get students from the course

First I will create the Student class. It has the FirstName and LastName property

Then I will create the Course class which implements the IEnumerable interface

Code explanation

  • Line 9: You can see the GetEnumerator() function which return the IEnumerator type

Now I am going to create StudentEnum class which implements the IEnumerator

In this class you have to implement Reset(), MoveNext(), Current()

Code explanation

  • Line   4: Position variable is used as the index of an array
  • Line   5: students() array to hold students
  • Line 10: Reset() function is used to reset the index position
  • Line 15: MoveNext() function is used to increase the position
  • Line 26: Current() function is used get the current object when you iterate

Now we can write the code to create some students objects and to the Course constructor method. Finally you can do the iterations