Method Overloading with Optional Parameter

前端 未结 3 1127
甜味超标
甜味超标 2021-01-17 07:56

I have a class as follows with two overload method.

Class A
{
    public string x(string a, string b)
    {
        return \"hello\" + a + b;
    }

    publ         


        
3条回答
  •  无人及你
    2021-01-17 08:05

    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.

提交回复
热议问题