Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enum parameter be optional in c#?

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 = ??)
 {
  ...
  }
like image 713
Cameron Castillo Avatar asked Mar 20 '15 08:03

Cameron Castillo


People also ask

What parameters are optional?

What are Optional Parameters? By definition, an Optional Parameter is a handy feature that enables programmers to pass less number of parameters to a function and assign a default value. Firstly, let us first understand what the word Optional Parameter means. Parameters are the names listed in the function definition.

Can enums have parameters?

You can have methods on enums which take parameters. Java enums are not union types like in some other languages.

Can you change the value of an enum in C?

You can change default values of enum elements during declaration (if necessary).

How do you pass an enum as an argument?

enums are technically descendants of Enum class. So, if you want to use only Enum's standard methods in your method (such as values()), pass the parameter like this: static void printEnumValue(Enum generalInformation) See, that the only thing you have to change is the capital letter E.


2 Answers

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) {

    }
}
like image 130
Mihail Shishkov Avatar answered Sep 23 '22 19:09

Mihail Shishkov


An enum is a value type, so you could use a nullable value type EnumColors?...

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

and then set the default value of EnumColors? to null

Another solution is to set EnumColors to an unused value...

void DoSomethingWithColors(EnumColors colors = (EnumColors)int.MinValue)
{
    if (colors != (EnumColors)int.MinValue) { Console.WriteLine(colors); }
}
like image 43
xanatos Avatar answered Sep 23 '22 19:09

xanatos