A_Sk
A_Sk

Reputation: 4630

Method Overloading with Optional Parameter

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?

Upvotes: 28

Views: 10927

Answers (3)

It will always execute method which first match with exact no of parameters, in your case it will execute :

Optional parameter method priority is less then the function with exact no of parameters

public string x(string a, string b);

Upvotes: 1

GorvGoyl
GorvGoyl

Reputation: 49190

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.

Upvotes: 31

andii1997
andii1997

Reputation: 259

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.

Upvotes: 4

Related Questions