I've used this helpful post to learn how to pass a list of Enum values as a parameter.
Now I would like to know whether I can make this parameter optional?
Example:
public enum EnumColors
{
[Flags]
Red = 1,
Green = 2,
Blue = 4,
Black = 8
}
I want to call my function that receives the Enum param like this:
DoSomethingWithColors(EnumColors.Red | EnumColors.Blue)
OR
DoSomethingWithColors()
My function should then look like what?
public void DoSomethingWithColors(EnumColors someColors = ??)
{
...
}
Yes it can be optional.
[Flags]
public enum Flags
{
F1 = 1,
F2 = 2
}
public void Func(Flags f = (Flags.F1 | Flags.F2)) {
// body
}
You can then call your function with or without parameter. If you call it without any parameter you'll get (Flags.F1 | Flags.F2)
as the default value passed to the f
parameter
If you don't want to have a default value but the parameter to be still optional you can do
public void Func(Flags? f = null) {
if (f.HasValue) {
}
}