Full Version: C# Flags
Dream.In.Code > Programming Tutorials > C# Tutorials
sontek
Using the [Flags] attribute on an enum allows to to perform bitwise operations on it so you can use to have settings for class.

This is especially usefull when a class can have multiple settings applied to it.

The example i'm using here is a Font, which can be Bold, Italic, or Underlined. So you'll notice I setup an enumeration with that special flags attribute.. One other thing you have to do is make the enumeration in powers of 2 (Because if you don't you'll do something like 1 | 2 == 3 which is another property of the Enum)

I hope this code helps ya guys out!
CODE

using System;
using System.Collections.Generic;
using System.Text;

namespace TestFlags
{
   class Program
   {
       static void Main(string[] args)
       {
           Font font = new Font();
           font.FontProps = FontProperties.Bold | FontProperties.Italic;

           Console.WriteLine(font.FontProps);
           Console.ReadLine();
       }
   }
   [Flags]
   public enum FontProperties
   {
       Bold = 1,
       Italic = 2,
       Underlined = 4,
       None = 8
   }
   public class Font
   {
       FontProperties fontProps;
       internal FontProperties FontProps
       {
           get { return fontProps; }
           set { fontProps = value; }
       }
       public Font()
       {
           fontProps = FontProperties.None;
       }
   }
}

graeme bradbury
It's rather bad practice to to have the "None" element of a flag enum to be a value other than 0.

This is because the literal constant 0 implicitly converts to any enum type and means "all bits zero"

So the properties enum is better being
CODE

[Flags]
public enum FontProperties
{
  None = 0,
  Bold = 1,
  Italic = 2,
  Underlined = 4
}


Something to also consider when using flags is to provide special enums for commonly used combinations. So in this example fonts are often bold and italic so the enum could look like
CODE

[Flags]
public enum FontProperties
{
  None = 0,
  Bold = 1,
  Italic = 2,
  BoldItalic = Bold | Italic,
  Underlined = 4
}
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2008 Invision Power Services, Inc.