Function overloading vs Optional Parameters

情到浓时终转凉″ 提交于 2019-12-04 10:14:56

I don't get is why it would be a more desirable option than using optional parameters

Parameters with default values have some limitations, which can be significant in some cases.

You can set default parameter for reference type, other than null (except string parameters):

class Foo
{
    public int Id { get; set; }
}

class Bar
{
    public Bar(Foo parent)
    {
    }

    public Bar()
        : this(new Foo { Id = 1 }) // this can't be done with default parameters
    {
    }
}

Parameters with default values can't appear before regular parameters, while this can be suitable sometimes:

class Foo
{
    public void Method(int i, string s, bool b) { }
    public void Method(string s, bool b) 
    {
        Method(0, s, b); // this can't be done with default parameters
    }
}

In your example the three overloads aren't equivalent to the method with optional parameters. setName(string last) states that the minimum data given is the last name, where public void setName(string first, string middle = "", string last = "") doesn't allow you to ommit first name. If you want to ommit middle name in the call of the method with optional parameters you would have to have setName("barack", last: "obama").

It would be somewhat better to have method with optional parameters like this:

public void setName(string last, string first= "", string middle = "")

But this ruins the natural order of names and allows you to set middle name without specifing first (setName("barack", middle: "hussein");) which the three overloads prohibit.

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