I have a class as follows with two overload method.
Class A { public string x(string a, string b) { return "hello" + a + b; } public string x(string a, string b, string c = "bye") { return c + a + b; } }
If I call the method x
from another class with two parameters, then which method is going to execute and why? i.e,
string result = new A().x("Fname", "Lname");
I've tested this in my console application and the method with 2 parameters execute. Can someone explain this?
By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.
The thing with optional parameters is, they are BAD because they are unintuitive - meaning they do NOT behave the way you would expect it. Here's why: They break ABI compatibility ! so you can change the default-arguments at one place.
Go doesn't support optional function parameters. This was an intentional decision by the language creators: One feature missing from Go is that it does not support default function arguments.
In the following example, I define the second parameter (secondNumber) as optional; Compiler will consider “0” as default value. Optional attribute always need to be defined in the end of the parameters list. One more ways we can implement optional parameters is using method overloading.
If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.
Reference: MSDN
Implying the above rule method with 2 parameters string x(string a,string b)
will be called.
Note: If both overloaded methods have optional parameters then compiler will give compile-time ambiguity error.
If you call the Method with two Parameters, it uses the Method with two Parameters. If you'd call the one with three, it would use the other.
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