1
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 :)

Ryan Johnson
  • 75
  • 11
  • 1
    Did you try `companyBit = (CompBitsList) 22;`. You could also create a `SetCompanyBit(int intValue)` function that just does the cast. But, you'll hate yourself in 5 years when you go back to maintain your code. The advantage of all that typing is that it is self documenting. – Flydog57 Sep 24 '19 at 19:41
  • Also, are you NOT using `[Flags]` for your enum, as this is obviously a bit flag enum? – Sach Sep 24 '19 at 19:48
  • @Sach Sorry I am just forgot to add it. – Ryan Johnson Sep 24 '19 at 19:49
  • @Flydog57 I think this may work lol I didn't imagine it would be that simple, and the only time I would be setting companyBit like that would be in the startup of the program by setting the value from an integer based on configurations. – Ryan Johnson Sep 24 '19 at 19:52
  • 1
    Here's some further reading. https://stackoverflow.com/questions/8447/what-does-the-flags-enum-attribute-mean-in-c – Sach Sep 24 '19 at 19:54
  • One thing you can do in configurations is parse a config string directly. If you have a config entry like `` (note the commas), then you can take that config string and parse it with `Enum.TryParse` and get a 22-valued `CompBitList` value directly. _(Note, this requires the `[Flags]` attribute on your enum)_ – Flydog57 Sep 24 '19 at 20:24
  • @Flydog57 Thanks for the tip! :) – Ryan Johnson Sep 24 '19 at 21:29

1 Answers1

2

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
}
Joshua Robinson
  • 3,399
  • 7
  • 22