Lex L
Lex L

Reputation: 315

Conditionally pass optional parameters in C#

I have a function with more than 10 optional parameters, and I have settings in my program to determine if a parameter should be passed or not. For example,

public void MyFunction(bool? b1=null, bool? b2=null, bool? b3=null.. bool? b10=null)

The following are the settings that dictate if parameters should be set or not

bool setb1 = false;
bool setb2 = false;
bool setb3 = true;
bool setb4 = false;
bool setb5 = true;

If I were to follow the settings to set parameters, then I will have to do something like this

if (!setb1 && !setb2 && !setb4)
   MyFunction(b3: value3, b5: value5);

If I have 10 settings and 10 parameters, then I will have too many combinations, so I don't think my implementation is feasible. What's the correct way to accomplish this?

Upvotes: 3

Views: 2069

Answers (1)

D-Shih
D-Shih

Reputation: 46229

Your function has a Long Parameter List

I would pass an object be the parameter, creating a class ConditionModle

You can encapsulate conditions you want in this class.

public class ConditionModle
{
    public bool setb1 { get; set; }
    public bool setb2 { get; set; }
    public bool setb3 { get; set; }
    public bool setb4 { get; set; }
    public bool setb5 { get; set; }
    ....
    public bool Condition1()
    {
        return !this.setb1 && !this.setb2 && !this.setb4;
    }
}

if (model.Condition1())
    MyFunction(model);

This solution could help your code

  1. Clearer,
  2. Add new property or judgment methods will not affect the previous method.
  3. Add new property you will not modify call method parameter.

Upvotes: 5

Related Questions