Alex Rivera | Logout

Really impossible to use return type overloading?

Asked 2009-09-26T12:45:00.037
12

I made a small DLL in MSIL with two methods:

float AddNumbers(int, int)
int AddNumbers(int, int)

As some of you might know, MSIL allows you to make methods that have the same arguments as long as you have different kinds of return types (what is called return type overloading). Now, when I tried to use it from c#, as I was kinda expecting, it fired an error:

float f = ILasm1.MainClass.AddNumbers(1, 2);

The error is:

The call is ambiguous between the following methods or properties: 'ILasm1.MainClass.AddNumbers(int, int)' and 'ILasm1.MainClass.AddNumbers(int, int)'

Is c# really incapable of distinguishing between different return types? I know I cannot program methods that have as only difference different return types, but I always kinda assumed it would know how to handle it.

Edit
Report

1 Answer

1

No, there's no way to do that. In fact, except in C++ with templates, no language is supporting it. This is just plainly too dangerous. And again, what if you write

var a = AddNumbers(1, 1);

what type a suppose to be?

Or what if you call it like

 double a = AddNumbers(1, 1);

or even

 AddNumbers(1, 1);

what version should it call?

Remember, there's quite complicate rules about how one type can be implicitly converted to another. Let's take a look at simple program that doesn't compile

class Program
{
    static int parse(int a) { return a; }
    static float parse(float a) { return a; }


    static void Main(string[] args)
    {
        double a = parse(1.0);
    }
}

If you try to compile it, compiler will give you an error

error C2668: 'parse' : ambiguous call to overloaded function
could be 'float parse(float)'

because 1.0 has type double and compiler really doesn't know what type to choose between int and float so it asks you to give it a hint. So you can just go ahead and convert an argument before calling a function.

But if it was return type that function is overloaded by, how do you do that then? There's simply no way of doing it.

answered 2009-09-26T13:09:06.930

Your Answer