Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Class need to implement IEnumerable to use Foreach

This is in C#, I have a class that I am using from some else's DLL. It does not implement IEnumerable but has 2 methods that pass back a IEnumerator. Is there a way I can use a foreach loop on these. The class I am using is sealed.

like image 898
Brian G Avatar asked Sep 24 '08 13:09

Brian G


People also ask

What must an object implement to use a for each loop?

The IEnumerable interface permits enumeration by using a foreach loop. However, the GetEmunerator method of the IEnumerable interface returns an IEnumerator interface. So to implement IEnumerable , you must also implement IEnumerator .

Does array implement IEnumerable?

All arrays implement IList, and IEnumerable. You can use the foreach statement to iterate through an array.

How is foreach implemented?

foreach isn't a function call - it's built-into the language itself, just like for loops and while loops. There's no need for it to return anything or "take" a function of any kind.


1 Answers

foreach does not require IEnumerable, contrary to popular belief. All it requires is a method GetEnumerator that returns any object that has the method MoveNext and the get-property Current with the appropriate signatures.

/EDIT: In your case, however, you're out of luck. You can trivially wrap your object, however, to make it enumerable:

class EnumerableWrapper {
    private readonly TheObjectType obj;

    public EnumerableWrapper(TheObjectType obj) {
        this.obj = obj;
    }

    public IEnumerator<YourType> GetEnumerator() {
        return obj.TheMethodReturningTheIEnumerator();
    }
}

// Called like this:

foreach (var xyz in new EnumerableWrapper(yourObj))
    …;

/EDIT: The following method, proposed by several people, does not work if the method returns an IEnumerator:

foreach (var yz in yourObj.MethodA())
    …;
like image 95
Konrad Rudolph Avatar answered Oct 13 '22 17:10

Konrad Rudolph