Can the enum parameter be optional in C #?

I used this useful post to learn how to pass a list of Enum values ​​as a parameter.

Now I would like to know if 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, which receives an Enum parameter, like this:

 DoSomethingWithColors(EnumColors.Red | EnumColors.Blue) 

OR

 DoSomethingWithColors() 

My function should look like this:

 public void DoSomethingWithColors(EnumColors someColors = ??) { ... } 
+5
source share
4 answers

Yes, this may not be necessary.

 [Flags] public enum Flags { F1 = 1, F2 = 2 } public void Func(Flags f = (Flags.F1 | Flags.F2)) { // body } 

Then you can call your function with or without a parameter. If you call it without any parameter, you will get (Flags.F1 | Flags.F2) as the default value passed to parameter f

If you do not want to have a default value, but the parameter is still optional, you can do

 public void Func(Flags? f = null) { if (f.HasValue) { } } 
+9
source

An enum is a value type, so can you use a value type with a zero value EnumColors? ...

 void DoSomethingWithColors(EnumColors? colors = null) { if (colors != null) { Console.WriteLine(colors.Value); } } 

and then set the default value to EnumColors? on null

Another solution is to set EnumColors unused value ...

 void DoSomethingWithColors(EnumColors colors = (EnumColors)int.MinValue) { if (colors != (EnumColors)int.MinValue) { Console.WriteLine(colors); } } 
+4
source

The following code is absolutely right.

 void colorfunc(EnumColors color = EnumColors.Black) { //whatever } 

The call can be made as follows:

 colorfunc(); colorfunc(EnumColors.Blue); 
+2
source

You can overload your function, so write two functions:

 void DoSomethingWithColors(EnumColors colors) { //DoWork } void DoSomethingWithColors() { //Do another Work, or call DoSomethingWithColors(DefaultEnum) } 
-1
source

Source: https://habr.com/ru/post/1215732/


All Articles