Method Overloading with Optional Parameter

北城以北 提交于 2019-12-01 13:42:51

问题


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?


回答1:


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.




回答2:


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.




回答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);


来源:https://stackoverflow.com/questions/39219180/method-overloading-with-optional-parameter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!