Flags Attribute for Enum Types

Problem
You want to know how to define enum types that contain a collection of flags instead of single values.

Solution
Mark them with the Flags attribute.

Comments
These types of enums are usually manipulated using bitwise operators. For example…

Example

using System;

namespace Playground
{
    internal static class Program
    {
        [Flags]
        private enum Colors
        {
            Red = 1,
            Blue = 2,
            Green = 4,
            Yellow = 8
        }

        public static void Main()
        {
            var textRepresentation = (Colors.Blue | Colors.Green).ToString();
            Console.WriteLine(textRepresentation);
            // Output is Blue, Green.
        }
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s