Programmer's Highway

C# Tips and simple code

I'm very sorry for machine translation in English.

C# How to use Enum

Definition of enum. The default type is Int32 Internally, the value is assigned from 0 in the order in which they were declared.

        enum DayOfWeek
            Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

Declare the type or value of the internal. In the example below will be of type uint, value is allocated from one.

        enum DayOfWeek : uint
            Sunday = 1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday

If you want to items such as drop-down list, To enumerate all the values in the Enum.GetValues method.

        foreach (var item in Enum.GetValues(typeof(DayOfWeek)))

If you want to convert enum value from a string, To callEnum.Parsemethod orEnum.TryParsemethod.

        // Enum.Parse()
        DayOfWeek w = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Sunday");
        // Enum.TryParse()
        Enum.TryParse<DayOfWeek>("Sunday"out w);

If you take more than one value, treated as a "bit field" attribute to external [Flags].

        enum DayOfWeek : byte
            Sunday = 0x01, Monday = 0x02, Tuesday = 0x04, Wednesday = 0x08, 
            Thursday = 0x10, Friday = 0x20, Saturday = 0x40

OR operator | can specify more than one in. And, Is a comma-delimited output as below then ToString().

        DayOfWeek weekend = DayOfWeek.Sunday | DayOfWeek.Saturday;
        Console.WriteLine(weekend.ToString());        // output: Sunday, Saturday

HasFlag method can Test the flags.

        public bool IsWeekend(DayOfWeek w)
            return w.HasFlag(DayOfWeek.Sunday | DayOfWeek.Saturday);
Visual Studio 2010 .NET Framework 4