简体   繁体   中英

Passing null as default parameter to avoid using parameter

I have created a function to set multiple properties of an object at once. If a certain argument isn't passed to the function then I want to avoid setting/changing it. A simplified example of the cleanest solution I could come up with is this:

private void setObjectProperties(MyObject myObject, float param1, bool? param2 = null)
{
    myObject.param1 = param1;
    myObject.param2 = param2 != null ? (bool)param2 : myObject.param2;
}

As you can see from this method, if the function is called without param2 being passed then it will just set myObject.param2 to itself. (meaning that if nothing is passed to param2 then the myObject.param2 property is untouched)

What I have seems a bit messy to me. I'm not sure if it is the 'correct' thing to do. I have thought about method overloading but I thought that this would be even messier; In the real world situation I am passing more than two arguments to be set so I could end up with a lot of overloads.

Am I missing some obvious functionality in C# that allows me to say "Don't set this parameter if nothing is passed to it's corresponding argument"?

Am I missing some obvious functionality in C# that allows me to say "Don't set this parameter if nothing is passed to it's corresponding argument"?

Not in a slick operator, but obviously you can do

if(param2.HasValue) myObject.param2 = (bool)param2;

The only real difference is if you have any logic in your setter it will not be called in this case if the parameter is null.

Try the null-coalescing operator ?? :

private void setObjectProperties(MyObject myObject, float param1, bool? param2 = null, bool? param3 = null)
{
    myObject.param1 = param1;
    myObject.param2 = param2 ?? myObject.param2;
    myObject.param3 = param3 ?? myObject.param3;
}

which you can invoke like

foo.setObjectProperties(myobj, param1,
       param2: p2, 
       param3: p3);

Do it like this:

private void setObjectProperties(float? param1 = null, bool? param2 = null)
{
    if (param1.HasValue) {
      this.param1 = param1.Value;
    }
    if (param2.HasValue) {
      this.param2 = param2.Value;
    }
}

Then:

MyObject myObject = new MyObject(); 
myObject.setObjectProperties(param1: 1.2f);
myObject.setObjectProperties(param2: true);
myObject.setObjectProperties(param1: 1.2f, param2: true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM