How to Implement an Interface that Requires Duplicate Member Names?
Posted
by Will Marcouiller
on Stack Overflow
See other posts from Stack Overflow
or by Will Marcouiller
Published on 2010-06-01T19:34:01Z
Indexed on
2010/06/01
22:03 UTC
Read the original article
Hit count: 236
I often have to implement some interfaces such as IEnumerable<T>
in my code.
Each time, when implementing automatically, I encounter the following:
public IEnumerator<T> GetEnumerator() {
// Code here...
}
public IEnumerator GetEnumerator1() {
// Code here...
}
Though I have to implement both GetEnumerator() methods, they impossibly can have the same name, even if we understand that they do the same, somehow. The compiler can't treat them as one being the overload of the other, because only the return type differs.
When doing so, I manage to set the GetEnumerator1()
accessor to private
. This way, the compiler doesn't complaint about not implementing the interface member, and I simply throw a NotImplementedException
within the method's body.
However, I wonder whether it is a good practice, or if I shall proceed differently, as perhaps a method alias or something like so.
What is the best approach while implementing an interface such as
IEnumerable<T>
that requires the implementation of two different methods with the same name?
EDIT #1
Does VB.NET reacts differently from C# while implementing interfaces, since in VB.NET it is explicitly implemented, thus forcing the
GetEnumerator1()
. Here's the code:
Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of T) Implements System.Collections.Generic.IEnumerable(Of T).GetEnumerator
// Code here...
End Function
Public Function GetEnumerator1() As System.Collections.Generic.IEnumerator Implements System.Collections.Generic.IEnumerable.GetEnumerator
// Code here...
End Function
Both GetEnumerator()
methods are explicitly implemented, and the compile will refuse them to have the same name. Why?
© Stack Overflow or respective owner