Search code examples
c#enumsflags

Setting enum flags from integer value


CompBitsList companyBit;
public CompBitsList CompanyBit { get => companyBit; set => companyBit= value; }

[Flags]
public enum CompBitsList
{
   None = 0
   BitOption1 = 1,
   BitOption2 = 2,
   BitOption3 = 4,
   BitOption4 = 8,
   BitOption5 = 16,
   BitOption6 = 32,
}

Lets say I have the integer value 22 that would contain the enum flags BitOption2, BitOption3 and BitOption5 (2+4+16). Is there a way to automate this so that I can pass the integer value and have the enum variable CompanyBit set automatically?

companyBit = CompBitsList.BitOption2 | CompBitsList.BitOption3 | CompBitsList.BitOption5

I'm not very familar with enums but I would prefer not to do the method above so any suggestions are appreciated. Thanks :)


Solution

  • You can just cast the int to an instance of CompBitsList.

    CompBitsList companyBit = (CompBitsList)22;
    companyBit.HasFlag(CompBitsList.BitOption2); // True
    companyBit.HasFlag(CompBitsList.BitOption3); // True
    companyBit.HasFlag(CompBitsList.BitOption5); // True
    companyBit.HasFlag(CompBitsList.BitOption6); // False
    

    You can also define a value on that enum that represents a combination of flags, if it makes sense and you'll be combining those flags a lot.

    [Flags]
    public enum CompBitsList
    {
       None = 0
       BitOption1 = 1,
       BitOption2 = 2,
       BitOption3 = 4,
       BitOption4 = 8,
       BitOption5 = 16,
       BitOption6 = 32,
       BitOptions2And3And5 = BitOption2 | BitOption3 | BitOption5 //or just 22
    }