I know I can't overload a return type (I think I know this).
void F()
{
}
bool F()
{
return true;
}
..produces error already defines a member called 'F' with the same parameter types
However, I'm reading the documentation for ISet from MSDN, and I think I see the two Add methods that only vary by return type.
What is going on here?
The first "Add" method is actually ICollection<T>.Add
, which is inherited.
When this is implemented in a class, at least one of the two Add
methods will need to be explicitly implemented, ie:
void ICollection<T>.Add(T item)
{
// ... Implement here
The other Add
method is an explicitly implemented interface method.
When an interface method is implemented explicitly, it cannot be called without casting the reference to the interface type first, which makes calls unambiguous, and therefore having multiple methods with the same signature is fine.
To do this in your code, you'd do, for instance
class MyCollection<T> : ICollection<T> {
public void Add() { ... }
void ICollection<T>.Add() { ... }
}
This avoids having to come up with alternate method names to avoid collisions with interface names, when you'd like the interface method to do something slightly differently than the other method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With