I have seen numerous posts debating about overloading a method by changing its return type, but, the following program should ideally work fine, because the variable i of type integer can only hold integer values.
So, it should ideally call the function int print(int a) function and not even look at the function float print(int a) because it returns a float value, and in main(), I have used an integer variable to hold the value returned by the method, and an integer variable can never hold a float value ..
The following code demonstrates it →
class temp
{
public float print(int a)
{
int l=12.55;
return l;
}
public int print(int a)
{
int p=5;
return p;
}
}
class Program
{
static void Main(string[] args)
{
temp t=new temp();
int i=t.print(10);
A.Read();
}
}
In other scenario, where I do something like this →
class temp
{
public float print(int a)
{
int l=12.55;
return l;
}
public int print(int a)
{
int p=5;
return p;
}
}
class Program
{
static void Main(string[] args)
{
temp t=new temp();
float f=t.print(10);
A.Read();
}
}
Here, I accept that the compiler should generate an error, because it falls in a dilemma whether to call public int(int a) or public float(int a), and because a variable of type float can holding both integer and float values ..
There is no return-type overloading in c#. What if you had ignored the return value, or assigned it to an Object? Then which overload would be called? There are so many ambiguous scenarios, this would be nearly impossible to implement.
It's not because of that, it's because of other scenarios.
For example, you know when you call Console.ReadLine() just to wait for user input? (e.g. press enter to continue)? Well, you could do the same with your print method in this case. Which one should it call then? Should it call the float method? Should it call the int method? What happens when they use var? dynamic? Generics?
You could argue that it should compile in your case, because you're not using it like that. However, what if it's in a class library? What if it's called through reflection? You can't just spend half of the compile-time checking whether it will be called anywhere else, without the return type.
And also, it wouldn't be good practice. You couldn't easily tell them apart, so you could cause so many bugs with this.
So in short: it's possible, but it's so, so impractical it would never be considered as wanted by language designers[1].
[1]: Interesting sidenote, MSIL allows it. So if you used ildasm, you could get return type overloading. Mainly because to call a function in it, you need to do this: call MyReturnType MyFunc(MyType, MyOtherType)
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