In this article I will explain about Enum, how to create and use Enum.
Definition: An enumeration is a set of related constants that define a value type where each constant is known as a member of the enumeration. The enumerations provided by the .NET Framework are generally used to set object properties and to specify the values that are passed to methods.
What is Enum?
An Enum is a value type with a set of related named constants often referred to as an enumerator list. The Enum keyword is used to declare an enumeration. It is a primitive data type, which is user defined.
Enums type can be Integer (Decimal, Short, Byte, Double etc.). To use one of the integer data types, you can code an As clause that specifies the data type after the enumeration name.
Enum is used to create numeric constants in .NET framework. All member of Enum are of Enum type. There must be a numeric value for each Enum type.
By default, an enumeration uses the Integer type and set the first constant to 0, the second to 1 and so on.
Syntax of declaring an enumeration
An enumeration defines a set of related constants. Each constant is known as a member of the enumeration.
To specify other values for the constants, you can code an equal sign after the constant name followed by the integer value.
Program to demonstrate how to create and Use an Enum:
Console.WriteLine("Day of week " & CInt(DayOfWeek.Sun) & " is " & DayOfWeek.Sun.ToString())
Console.WriteLine("Day of week " & CInt(DayOfWeek.Mon) & " is " & DayOfWeek.Mon.ToString())
Console.WriteLine("Day of week " & CInt(DayOfWeek.Tue) & " is " & DayOfWeek.Tue.ToString())
Console.WriteLine("Day of week " & CInt(DayOfWeek.Thu) & " is " & DayOfWeek.Wed.ToString())
Console.WriteLine("Day of week " & CInt(DayOfWeek.Fri) & " is " & DayOfWeek.Thu.ToString())
Console.WriteLine("Day of week " & CInt(DayOfWeek.Sat) & " is " & DayOfWeek.Fri.ToString())
The output of above program:
Some points about Enum:
- Enums are enumerated data type in VB.NET.
- Enums are not for end-user, they are meant for developers.
- Enums are strongly typed constant. They are strongly typed, i.e. an Enum of one type may not be implicitly assigned to an Enum of another type even though the underlying value of their members are the same.
- Enumerations (Enums) make your code much more readable and understandable.
- Enum values are fixed. Enum can be displayed as a string and processed as an Integer.
- The default type is Integer, and the approved types are Byte, Sbyte, Short, UShort, UInteger, Long, and ULong.
- Every Enum type automatically derives from System.Enum and thus we can use System.Enum methods on Enums.
- Enums are value types and are created on the stack and not on the heap.
- The default and only access modifier supported is public.
You give two same values in Enum type?
Yes we can have same value in Enum type. Example when we want to set priority options like
Hope the article would have helped you in understanding Enum and their usage.