Page 1 of 1

C# Flags Howto use flags to create settings

#1 sontek  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 8
  • View blog
  • Posts: 283
  • Joined: 13-September 01

Posted 04 April 2006 - 04:42 AM

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!
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;
        }
    }
}




Is This A Good Question/Topic? 1
  • +

Replies To: C# Flags

#2 graeme bradbury  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 28-June 07

Posted 09 August 2007 - 02:31 AM

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
[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
[Flags]
public enum FontProperties
{
  None = 0,
  Bold = 1,
  Italic = 2,
  BoldItalic = Bold | Italic,
  Underlined = 4
}


This post has been edited by graeme bradbury: 09 August 2007 - 02:32 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1