Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface with members with same name and different return types

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(); 
}
like image 914
Sam Leach Avatar asked Aug 23 '26 10:08

Sam Leach


2 Answers

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.

like image 171
Joni Avatar answered Aug 26 '26 00:08

Joni


What if you decided to code the following:

var x = Receive();

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

like image 28
Ric Avatar answered Aug 26 '26 00:08

Ric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!