Posted By

jimfred on 09/14/09


Tagged


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

danfinrud55


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


 / Published in: C#
 

URL: http://msdn.microsoft.com/en-us/library/system.flagsattribute%28VS.71%29.aspx

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.

  1. // Given this enum...
  2. [FlagsAttribute]
  3. enum MyStatus: ushort
  4. {
  5. Bit0 = 0x0000,
  6. Bit1 = 0x0001,
  7. Bit2 = 0x0002,
  8. Bit3 = 0x0004
  9. };
  10.  
  11.  
  12. // Cast a 0x7 to MyStatus and render a string for testing/demonstration purposes:
  13. ((MyStatus)0x7).ToString() results in string "Bit0, Bit1, Bit2"
  14.  
  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  

You need to login to post a comment.