Home > OS >  Can I pass a value to an optional parameter to indicate I want the parameter to be set to default?
Can I pass a value to an optional parameter to indicate I want the parameter to be set to default?

Time:07-21

I have a couple of external functions, one has an enum with a list of colours which do not correspond to System.Drawing.Color, this enum also provides "default" as one of its options.

I have a second external function which takes a lot of arguments, one being an optional System.Drawing.Color. If this is not provided, it uses the next colour in its internal list, which I don't have access to.

At the moment I'm doing an if statement, if default then I just pass nothing, else pass a helper functions output. It looks something like:

if (extEnum == LimitedColor.Default){
    extFunction();
} else {
    extFunction(GetColor(extEnum));
}

Where GetColor is a simple switch statement to translate LimitedColor to System.Drawing.Color.

Is there a simpler way to achieve this inline?

I was hoping that the default keyword would do this, but it seems to only be useful in generating the default initialised value of a given class as per this page - unless I have misunderstood this completely.

CodePudding user response:

If you've only got a couple external functions then I'd stick them in a wrapper class and only call that class' methods. Then the wrapper runs your if statement/conversion for you.

CodePudding user response:

Is there a simpler way to achieve this inline?

Not really. There is no way to explicitly use the default value:

// Not possible
extFunction(color: some_special_word_to_say_use_default_value);

However, in case

  • extFunction(Color? color = null) or
  • ~extFunction(Color color = Color.None)

you could:

extFunction(
     color: (extEnum != LimitedColor.Default) ? GetColor(extEnum) : null); // or Color.None
  •  Tags:  
  • c#
  • Related