April 21, 2005

Using Enumerated Types in C# as Bit Flags

example

[Flags]
  public enum Layout : byte //<= specify UNDERLYING type here
  {
    CentreColumn = 1,
    LeftColumn = 2,
    RightColumn = 4
  }
  
  private Layout m_Layout = Layout.CentreColumn | Layout.LeftColumn
| Layout.RightColumn; ... // USAGE m_Layout.ToString(); // => Gives "'CentreColumn, LeftColumn, RightColumn'" // Going the other way Layout m_Layout = (Layout)Enum.Parse(typeof(Layout), "CentreColumn, LeftColumn"); Layout m_Layout = (Layout)4; // => m_Layout = RightColumn

No comments: