Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does ISet have two Add(T item) methods that vary only by return type?

Tags:

c#

collections

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?

like image 740
Aaron Anodide Avatar asked Feb 10 '12 00:02

Aaron Anodide


2 Answers

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
like image 109
Reed Copsey Avatar answered Sep 20 '22 04:09

Reed Copsey


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.

like image 29
Matti Virkkunen Avatar answered Sep 20 '22 04:09

Matti Virkkunen