Click here to Skip to main content
15,895,142 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
The code:
C#
class Person
   {
       public string FirstName { get; set; }
       public string LastName { get; set; }
       public Person(string firstName, string lastName)
       {
           FirstName = firstName;
           LastName = lastName;
       }
       public override string ToString()
       {
           return FirstName + " " + LastName;
       }
   }
   class People : IEnumerable<Person>
   {
       Person[] people;
       public People(Person[] people)
       {
           this.people = people;
       }
       public IEnumerator<Person> GetEnumerator()
       {
           for (int i = 0; i < people.Length; i++)
           {
               yield return people[i];
           }
       }
       IEnumerator IEnumerable.GetEnumerator()
       {
           return GetEnumerator();
       }
   }

So class People implemented the interface IEnumerable. What I am confused is the two methods(Can we call them methods?).
C#
public IEnumerator<Person> GetEnumerator()
        {
            for (int i = 0; i < people.Length; i++)
            {
                yield return people[i];
            }
        }
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

Should we call them methods? Because IEnumerable has the default method GetEnumerator.
We can directly use it. If we change the behavior then we need to add the override modifier.
Should we:
C#
public override GetEnumerator()
{
 //blah blah
}
Posted

1 solution

Yes, they are methods. When you call them via IEnumerable (for example by using foreach) you are calling your version of them, since IEnumerable is an interface and doesn't implement any code at all itself. That's why you have to implement them: so that they are there to be called!

Yes, you could call them yourself: but you don't normally have to. The code that requires you to add the interface to your class calls them for you in nearly all cases.
 
Share this answer
 
Comments
[no name] 9-Jan-15 11:38am    
So why miss override keyword?
Richard Deeming 9-Jan-15 11:42am    
Because override is only required when there is a virtual method with the same signature defined in the base class. In your example, there isn't a base class, so you don't need to override anything.
OriginalGriff 9-Jan-15 11:43am    
Because it's an interface you are implementing, and an interface - by definition - includes no code whatsoever. So there is no existing method to override!

Including the keyword "override" would imply that it will work (or at least compile) if you didn't include your version!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900