Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Overloading with Optional Parameter

Tags:

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?

like image 992
A_Sk Avatar asked Aug 30 '16 05:08

A_Sk


People also ask

How do you pass optional parameters to a method?

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.

Are optional parameters bad practice?

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.

Can go have optional parameters?

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.

How do you add optional parameters?

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.


2 Answers

Use of named and optional arguments affects overload resolution:

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.

like image 144
GorvGoyl Avatar answered Nov 20 '22 21:11

GorvGoyl


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.

like image 31
andii1997 Avatar answered Nov 20 '22 21:11

andii1997