IEnumerable<T> interface

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • =?Utf-8?B?UElFQkFMRA==?=

    IEnumerable<T> interface

    [When I tried posting this there was an error, I apologize if this is a
    duplicate.]

    Something I found surprising this week involves the IEnumerable<Tin terface.
    I have a class that I wrote a couple of years ago which implements the
    IEnumerable interface. This week I realized it should implement
    IEnumerable<T>.

    But when I changed the return type of the GetEnumerator method the compiler
    said the class no longer implemented IEnumerable.

    IEnumerable<Tha s IEnumerable as a base interface, so I had assumed that
    implementing IEnumerable<Two uld satisfy IEnumerable as well. After some
    time wrestling with this I finally tried implementing both interfaces
    explicitly even though both do the same exact thing:

    IEnumerator<TIE numerable<T>.Ge tEnumerator ...
    IEnumerator IEnumerable.Get Enumerator ...

    Much to my surprise, it works.

    While I realize that inheritance and IS_A don't apply to interfaces, this
    seems counter-intuitive; shouldn't a method that returns IEnumerable<T>
    satisfy IEnumerable?

  • Peter Duniho

    #2
    Re: IEnumerable&lt; T&gt; interface

    On Sun, 03 Aug 2008 17:31:07 -0700, PIEBALD
    <PIEBALD@discus sions.microsoft .comwrote:
    [...]
    While I realize that inheritance and IS_A don't apply to interfaces, this
    seems counter-intuitive; shouldn't a method that returns IEnumerable<T>
    satisfy IEnumerable?
    C# doesn't have return-type covariance (it's missing lots of other kinds
    of variance too...IMHO the language mostly benefits from that, because it
    keeps things simple).

    There are languages in which what you tried would work. But in C# you
    have to be explicit about it. Fortunately, it's as simple as just having
    one of your GetEnumerator() methods return the other.

    Pete

    Comment

    Working...