Question

Why can I not do the following?

public interface ICommunication
{
    int Send(Dictionary<string, string> d);
    int Send(byte[] b);

    Dictionary<string, string> Receive();
    byte[] Receive(); // Error
}

The signarure of Receive() is different but the parameters are the same. Why does the compiler look at the parameters and not the member signature?

ICommunication' already defines a member called 'Receive' with the same parameter types.

How could I get around this?

I could rename Receive() as below but I'd prefer to keep it named Receive().

public interface ICommunication
{
    int Send(Dictionary<string, string> d);
    int Send(byte[] b);

    Dictionary<string, string> ReceiveDictionary();
    byte[] ReceiveBytes(); 
}
Was it helpful?

Solution

The return type is not part of the method signature, so from the language perspective the interface is declaring the same method twice.

From Microsoft's C# Programming Guide:

A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.

OTHER TIPS

What if you decided to code the following:

var x = Receive();

what method should it use? what is the return type?

It is not allowed in C# because when you call it with Receive() how does System knows which Method to call?

Call returning Dictionary or byte array?

So Designers made it not supported

eg: var returnVal = ICommunication.Receive()

EDIT:

public interface ICommunication
{
    int Send(Dictionary<string, string> d);
    int Send(byte[] b);

   void Receive(out Dictionary<string, string>);
   void Receive(out byte[]); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top