Beau Beau - 3 months ago 7
C# Question

C# Flagged Enums: how to append value

So, I have a flagged enum:

[Flags]
public enum EmailResult
{
ISPUSuccess = 1,
STSSuccess = 2
}


What I want to do is, via conditonals, set an enum var to one, the other, or both.

As in,

If (ISPU){
Result = EmailResult.ISPUSuccess
}
If (STS){
Result += EmailResult.STSSuccess
}


Like adding.. so it would effectively be

Result = EmailResult.ISPUSuccess | EmailResult.STSSuccess

Answer

You use the |= operator to set your values in an enum marked with the [Flags] attribute.

[Flags]
public enum EmailResult
{
    None = 0,
    ISPUSuccess = 1,
    STSSuccess = 2
}

EmailResult result = EmailResult.None;

if(.... your condition ....)
   result |= EmailResult.ISPUSuccess;

if( .... other condition ...)
   result |= EmailResult.STSSuccess;

Console.WriteLine(result); // -> ISPUSuccess, STSSuccess

if((result & EmailResult.STSSuccess) != EmailResult.None)
   ..... flag is set ...

Notice that I have added another enum with value 0 to use in conditions where I need to check the current state of a particular flag.

Comments