tags:

views:

444

answers:

2

In any class, how do I explicitly refer to a certain method of my class?

For example, this code works:

class Test : IEnumerable<T> {
    public IEnumerator<T> GetEnumerator() { return null; }
    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
}

But this one doesn't!

class Test : IEnumerable<T> {
    IEnumerator<T> IEnumerable<T>.GetEnumerator() { return null; }
    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } // error
}

How do I refer to the generic version of my method? In Java I would simply prefix it with the interface name, but this does't seem to work in C#. Is there a way to do this, other than ((IEnumerable<T>)this).GetEnumerator()?

EDIT: I'm not interested in "why" it does't work this way. I'm just looking for a way to do it. Thanks.

+2  A: 

If you use explicit interface implementation, you need to access the method through that interface.

So no, there is no way other than what you propose in the text.

In this case though you will typically not use explicit implementation for the generic interface.

Edit: If the documentation warning is the source of your concerns, let me give you a much better advice: GhostDoc.

If you install this, and bind it to, say, Shift+Ctrl+D (default), then it will try to understand the name of your methods and add the necessary documentation. This isn't the good part, since you should always edit this part yourself, but if you inherit methods and properties from either a base class, or as in your case, an interface, it will copy the documentation automatically. Sometimes you need to edit it to make it more specific to your type, but usually you can just leave it.

It will also have special detection of typical patterns.

Try it, I'm sure you'll love it.

Lasse V. Karlsen
Thanks. I wanted to use explicit interface implementation because it removes the compiler's warning for "undocumented public method". It seems I'll have to copy its documentation! :s Long live Java!
Hosam Aly
+1  A: 

Well, you can cast...

    IEnumerator<T> IEnumerable<T>.GetEnumerator() { return null; } // TODO
    IEnumerator IEnumerable.GetEnumerator() {
        return ((IEnumerable<T>)this).GetEnumerator();
    }

or you can use a non-public instance method for both:

    IEnumerator<T> IEnumerable<T>.GetEnumerator() { return GetEnumerator(); }
    IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
    private IEnumerator<T> GetEnumerator() { return null; } // TODO

Personally, though, I prefer to see a public GetEnumerator() - same as I like a public Dispose() - it makes it easier for the consumer to know it is there. I don't think all interface implementations should be public (far from it), but foreach and using are so fundamental that a little advertising doesn't hurt.

Marc Gravell