Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cascade optional parameter?

I have a worker method with an optional parameter

Work(string input = DefaultInput)
{
    //do stuff
}

And I have a wrapper around this, which also take the string input, but this can also be optional...

WorkWrapper(int someParameter, string input = DefaultInput)
{
    //do initialization
    Work(input);

}

The problem here is I duplicate reference to DefaultInput, if, say, I change the default input of work to NewDefaultInput, I will need to update the workWrapper as well, otherwise it will still use the old default.

Is there a way so that the default input do not need to be declared twice? Possibly without having two overloads for workwrapper..

like image 317
Louis Rhys Avatar asked Apr 17 '26 20:04

Louis Rhys


1 Answers

If you want the defaults to be in sync between the two methods, you really don't need the default in the wrapper, right?

public void Work(string input = DefaultInput)
{
    //do stuff
}

public void WorkWrapper(int someParameter, string inputOverride = null)
{
    //do initialization

    if (inputOverride == null) Work();
    else Work(inputOverride);    
}

If they are in the same class/hierarchy, you could also just declare a const to ensure that the defaults remain the same.

private const string DEFAULT_INPUT = "Default Input"; // protected if in base class

public void Work(string input = DEFAULT_INPUT)
{
    //do stuff
}

public void WorkWrapper(int someParameter, string input = DEFAULT_INPUT)
{
    //do initialization
    Work(input);    
}
like image 171
Jay Avatar answered Apr 19 '26 09:04

Jay