Shows How to use Both Bit Fields and Traditional Enumerations

Introduction

The FlagsAttribute attribute denotes a special kind of enumeration called a bit field. The runtime itself does not distinguish between traditional enumerations and bit fields, but your language might do so. When this distinction is made, bitwise operators can be used on bit fields, but not on enumerations, to generate unnamed values. Enumerations are generally used for lists of unique elements, such as days of the week, country or region names, and so on. Bit fields are generally used for lists of qualities or quantities that might occur in combination, such as Red And Big And Fast.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Management;

using System.Reflection;

using System.Data.SqlClient;

using System.Data;

using System.Text.RegularExpressions;

using System.Data.Sql;

using System.ServiceProcess;

using System.Net;

using System.Net.Mail;

namespace MyRND

{

    class Program

    {

        public enum Vegetables

        {

            HorseRadish,

            Radish,

            Turnip

        }

        [Flags]

        public enum Seasons

        {

            None = 0,

            Summer = 1,

            Autumn = 2,

            Winter = 4,

            Spring = 8,

            All = Summer | Autumn | Winter | Spring

        }

        static void Main(string[] args)

        {

            Dictionary<Vegetables, Seasons> AvailableIn = new Dictionary<Vegetables, Seasons>();

            AvailableIn[Vegetables.HorseRadish] = Seasons.All;

            AvailableIn[Vegetables.Radish] = Seasons.Spring;

            AvailableIn[Vegetables.Turnip] = Seasons.Spring |

            Seasons.Autumn;

            Seasons[] theSeasons = new Seasons[] { Seasons.Summer, Seasons.Autumn,

            Seasons.Winter, Seasons.Spring };

            foreach (Seasons season in theSeasons)

            {

                Console.Write(String.Format(

                "The following Vegetables are harvested in {0}:\n",

                season.ToString("G")));

                foreach (KeyValuePair<Vegetables, Seasons> item in AvailableIn)

                {

                    // A bitwise comparison.

                    if (((Seasons)item.Value & season) > 0)

                        Console.Write(String.Format(" {0:G}\n",

                        (Vegetables)item.Key));

                }

            }

            Console.ReadLine();

        }

    }

}