There are scenarios when you don't want to expose something on the public API in the direct form. Maybe it will never work; maybe the public API can expose a more appropriate signature of the same functionality. For example:
public int Add(Foo foo) {...} // takes a known type and returns the new index
void ICollection.Add(object obj) {...} // takes object and returns void
A more common example is when it would be impossible not to - for example, IEnumerable
and IEnumerable<T>
each have a GetEnumerator()
method - same inputs, but a different return value. C# does not allow overloading by return value, so you need at least two methods:
IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); }
public IEnumerator<T> GetEnumerator() { ...}
although they could also both be explicit. Or indeed, in IEnumerator<T>
:
public T Current { get { ... } }
object IEnumerator.Current { get { return Current; } }
Additionally, sometimes you just want to rename things. For example, for some reason a Frobber
has a method which naturally is Frob()
. But it also implements an IDoSomething
interface which has a DoIt()
method; you can now make the APIs reflect the most appropriate terminology to express intent:
class Frobber : IDoSomething {
public void Frob() {..}
void IDoSomething.DoIt() { Frob(); }
}