How is the for each in C # used? [closed]

-1

I am studying OOP in the faculty and I do not finish understanding objects, and now I am having problems with the for each, I understand that it is to go through objects, but I do not understand the function well. If you could recommend some book or tutorials I would be very grateful.

    
asked by Horacio Mansilla 29.10.2018 в 16:57
source

1 answer

2

The foreach statement is a way to traverse each element within an object, the advantage being that your code does not need to know the internal structure of the east. The person responsible for delivering the objects in order is the same class that you are iterating.

The only requirements to be able to use foreach on an instance are:

  • The class implements a public method called GetEnumerator()
  • The object that returns GetEnumerator() implements property Current and method MoveNext()

These conditions are forced to be met if the interface IEnumerable or IEnumerable<T> is implemented.

There are many classes in the .NET framework that already implement these interfaces as List<T> and Array , you will not need to implement it yourself in most cases.

    
answered by 29.10.2018 в 17:22