Tutorial by Examples

enum MyEnum { One, Two, Three } foreach(MyEnum e in Enum.GetValues(typeof(MyEnum))) Console.WriteLine(e); This will print: One Two Three
The FlagsAttribute can be applied to an enum changing the behaviour of the ToString() to match the nature of the enum: [Flags] enum MyEnum { //None = 0, can be used but not combined in bitwise operations FlagA = 1, FlagB = 2, FlagC = 4, FlagD = 8 //you must use pow...
A flags-style enum value needs to be tested with bitwise logic because it may not match any single value. [Flags] enum FlagsEnum { Option1 = 1, Option2 = 2, Option3 = 4, Option2And3 = Option2 | Option3; Default = Option1 | Option3, } The Default value is actually a ...
public enum DayOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday } // Enum to string string thursday = DayOfWeek.Thursday.ToString(); // "Thursday" string seventhDay = Enum.GetName(typeof(DayOfWeek), 6); // "Satur...
The default value for an enum is zero. If an enum does not define an item with a value of zero, its default value will be zero. public class Program { enum EnumExample { one = 1, two = 2 } public void Main() { var e =...
From MSDN: An enumeration type (also named an enumeration or an enum) provides an efficient way to define a set of named integral constants that may be assigned to a variable. Essentially, an enum is a type that only allows a set of finite options, and each option corresponds to a number. By d...
The FlagsAttribute should be used whenever the enumerable represents a collection of flags, rather than a single value. The numeric value assigned to each enum value helps when manipulating enums using bitwise operators. Example 1 : With [Flags] [Flags] enum Colors { Red=1, Blue=2, ...
The left-shift operator (<<) can be used in flag enum declarations to ensure that each flag has exactly one 1 in binary representation, as flags should. This also helps to improve readability of large enums with plenty of flags in them. [Flags] public enum MyEnum { None = 0, Fl...
In some cases you might want to add an additional description to an enum value, for instance when the enum value itself is less readable than what you might want to display to the user. In such cases you can use the System.ComponentModel.DescriptionAttribute class. For example: public enum Possibl...
This code is to add and remove a value from a flagged enum-instance: [Flags] public enum MyEnum { Flag1 = 1 << 0, Flag2 = 1 << 1, Flag3 = 1 << 2 } var value = MyEnum.Flag1; // set additional value value |= MyEnum.Flag2; //value is now Flag1, Flag2 value...
Since an enum can be cast to and from its underlying integral type, the value may fall outside the range of values given in the definition of the enum type. Although the below enum type DaysOfWeek only has 7 defined values, it can still hold any int value. public enum DaysOfWeek { Monday = 1...

Page 1 of 1