Core C#

Enums as Flags

This C# program demonstrates how to program with enums as flags in C#.

Program.cs

using System;

namespace Enumerations {

    [Flags]
    enum EDays {
        keNone = 0x0,
        keSunday = 0x1,
        keMonday = 0x2,
        keTuesday = 0x4,
        keWednesday = 0x8,
        keThursday = 0x10,
        keFriday = 0x20,
        keSaturday = 0x40
    }

    class Program {
        static void Main(string[] args) {
            string s = Enum.GetName(typeof(EDays), 4);
            Console.WriteLine(s);
            Console.WriteLine();

            Console.WriteLine("The integer values of the Days Enum are:");
            foreach (int i in Enum.GetValues(typeof(EDays))) {
                Console.Write(i + "  ");
            }
            Console.WriteLine("\n");

            Console.WriteLine("The names of the Days Enum are:");
            foreach (string str in Enum.GetNames(typeof(EDays))) {
                Console.Write(str + "  ");
            }
            Console.WriteLine("\n");

            Console.WriteLine("Iterate through all day combinations up to keWednesday:");
            for (EDays eDay = EDays.keNone; eDay < EDays.keWednesday; ++eDay) {
                Console.WriteLine(eDay);
            }
            Console.WriteLine();

            Console.WriteLine("The days of the weekend are:");
            EDays eWeekendDays = EDays.keSaturday | EDays.keSunday;
            Console.WriteLine(eWeekendDays + "\n");

            Console.WriteLine("The weekdays are:");
            EDays eWeekdays = EDays.keMonday | EDays.keTuesday | EDays.keWednesday | EDays.keThursday | EDays.keFriday;
            Console.WriteLine(eWeekdays + "\n");
        }
    }
}
 

Output

keTuesday

The integer values of the Days Enum are:
0  1  2  4  8  16  32  64

The names of the Days Enum are:
keNone  keSunday  keMonday  keTuesday  keWednesday  keThursday  keFriday  keSaturday

Iterate through all day combinations up to keWednesday:
keNone
keSunday
keMonday
keSunday, keMonday
keTuesday
keSunday, keTuesday
keMonday, keTuesday
keSunday, keMonday, keTuesday

The days of the weekend are:
keSunday, keSaturday

The weekdays are:
keMonday, keTuesday, keWednesday, keThursday, keFriday

Press any key to continue . . .
 
 

© 2007–2025 XoaX.net LLC. All rights reserved.