Render names of C# bitfields using enums and FlagsAttribute. Also, adjusting size of enum using, like ushort, for marshalling p

/ Published in: C#
Save to your folder(s)

FlagsAttribute is useful to render a string indicating which status bits or flag bits are turned on. The resulting string will contain the name of the enum bit that is turned on without needed to maintain a separate string table.

Note the inheritance-like syntax that determines the size of the enum. This is useful to adjust the size of enum structure members for marshaling with C.

Copy this code and paste it in your HTML
  1. // Given this enum...
  2. [FlagsAttribute]
  3. enum MyStatus: ushort
  4. {
  5. Bit0 = 0x0000,
  6. Bit1 = 0x0001,
  7. Bit2 = 0x0002,
  8. Bit3 = 0x0004
  9. };
  12. // Cast a 0x7 to MyStatus and render a string for testing/demonstration purposes:
  13. ((MyStatus)0x7).ToString() results in string "Bit0, Bit1, Bit2"
  15. // To test a bit, use code of the form. Assumes status is a MyStatus.
  16. if ( Convert.ToBoolean( status & MyStatus.Bit0) )


Report this snippet


RSS Icon Subscribe to comments

You need to login to post a comment.