Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two GetEnumerator methods?

Tags:

c#

.net

I really can't understand why, in this example, this class defines two GetEnumerator methods: one explicitly implementing the interface and the other one implicitly as I got it. So why?

class FormattedAddresses : IEnumerable<string>
{
    private List<string> internalList = new List<string>();

    public IEnumerator<string> GetEnumerator()
    {
        return internalList.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return internalList.GetEnumerator();
    }

    public void Add(string firstname, string lastname,
                    string street, string city,
                    string state, string zipcode)
    {
        internalList.Add($@"{firstname} {lastname} {street} {city}, {state} {zipcode}");
    }
}
like image 486
Ruslan Plastun Avatar asked Jan 28 '26 15:01

Ruslan Plastun


1 Answers

why [...] this class defines two GetEnumerator methods:

Well, one is generic, the other is not.
The non-generic version is a relic from .NET v1, before generics.

You have class FormattedAddresses : IEnumerable<string> but IEnumerable<T> derives from the old interface IEnumerable.

So it effectively is class FormattedAddresses : IEnumerable<string>, IEnumerable and your class has to implement both. The two methods differ in their return Type so overloading or overriding are not applicable.

Note that the legacy version is implemented 'explicitly', hiding it as much as possible and it is often acceptable to not implement it:

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
    throw new NotImplemented();
}

Only in a full blown library class (as opposed to an application class) would you bother to make it actually work.

like image 148
Henk Holterman Avatar answered Jan 30 '26 05:01

Henk Holterman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!