In C#, there are three different types of enums available:
-
Numeric Enums: Numeric enums are the most common type of enum in C#. They associate a set of named constants with underlying numeric values. The underlying type can be any integral type (
byte
,sbyte
,short
,ushort
,int
,uint
,long
, orulong
). If you don't specify an underlying type explicitly, the default isint
.
csharpCopy code public enum NumericEnum : byte { Value1 = 1, Value2 = 2, Value3 = 3 }
-
String Enums: String enums were introduced in C# 10 (.NET 7). They allow you to define an enum where the underlying type is
string
. This can be useful in scenarios where you need to work with string-based representations rather than numeric values.
csharpCopy code public enum StringEnum : string { Value1 = "One", Value2 = "Two", Value3 = "Three" }
-
Flags Enums: Flags enums are used when you want to represent combinations or sets of options as bit flags. This allows you to perform bitwise operations on the enum values. To create a flags enum, you need to decorate it with the
[Flags]
attribute and assign each enum value a unique power of 2 (or use the<<
operator).
csharpCopy code [Flags] public enum FlagsEnum { None = 0, Option1 = 1, Option2 = 2, Option3 = 4, Option4 = 8 }
Flags
enums can be combined using bitwise OR (|
)
and checked for the presence of specific flags using bitwise AND (&
)
or the HasFlag
method.
These are the three types of enums in C#: numeric enums, string enums (from C# 10), and flags enums. Each type serves a specific purpose and allows you to define enums with different underlying types and behaviors.