In C# programming, the Enum, short for enumeration, serves as a container for a collection of named constants like days of the week, months, sizes, etc. These named constants within an Enum are referred to as enumerators. Enums can be defined inside or outside classes and structs in C# by using the enum keyword. They allow developers to establish a cluster of associated symbolic identifiers denoting various conditions or choices within their code.
Enum constants are automatically assigned default values starting from 0 and increasing by 1 for each subsequent constant. Nevertheless, it is possible to assign custom values explicitly if needed.
For instance, we have the option to define an enumeration called Seasons, which includes Winter, Spring, Summer, and Fall, as an alternative to numerical representations like 0, 1, 2, and 3 for different seasons.
Syntax of Enum
It has the following syntax:
enum EnumName
{
Value1,
Value2,
Value3,
// ...
}
In this particular syntax,
- EnumName signifies the title of the Enumeration.
C# Enum Example
Let's consider a scenario to demonstrate the enum in C# programming.
Example
using System;
public class EnumExample
{
public enum Season
{
WINTER,
SPRING,
SUMMER,
FALL
}
public static void Main()
{
int x = (int)Season.WINTER;
int y = (int)Season.SUMMER;
Console.WriteLine("WINTER = {0}", x);
Console.WriteLine("SUMMER = {0}", y);
}
}
Output:
WINTER = 0
SUMMER = 2
Explanation:
In this instance, we define an enumeration named Season comprising of four constants. Within the Main function, it converts specific enum elements (WINTER and SUMMER) to integer values and displays their corresponding numeric representations. WINTER is conventionally assigned 0, SPRING is 1, SUMMER is 2, and FALL is 3, resulting in the output of 0 for WINTER and 2 for SUMMER.
Features of C# Enum
There are several important features of the C# Enum. Some of them are as follows:
- Enumeration can be declared with the enum keyword within a class, namespace, or structure.
- It is used to define a set of named constants.
- Enum members should be unique inside the same enum.
- It can be utilized to define the custom integrals for the strings.
- By default, the enum base type is int.
- It can be utilized in switch statements.
- Enum members are by default public, static, and constant.
Enum Inside a Class
In C# development, an enumeration can be declared within a class as well. Let's consider a demonstration to showcase the Enum within the class and modifying the position of an item.
Example
using System;
public class EnumExample
{
public enum Season {
WINTER=10,
SPRING=11,
SUMMER=12,
FALL=13
}
public static void Main()
{
int x = (int)Season.WINTER;
int y = (int)Season.SUMMER;
Console.WriteLine("WINTER = {0}", x);
Console.WriteLine("SUMMER = {0}", y);
}
}
Output:
WINTER = 10
SUMMER = 12
Explanation:
In this illustration, we define an enumeration called Season where WINTER is assigned the integer value 10, causing the following members to increment automatically. Within the main function, it converts the WINTER and SUMMER enums to integers and displays them. The result will show WINTER as 10 and SUMMER as 12.
C# Enum Example for Days (Declared Inside a Class)
Let's consider an instance where the days of the week are defined within a class in C#.
Example
using System;
public class EnumExample
{
public enum Days {
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
public static void Main()
{
int x = (int)Days.Sun;
int y = (int)Days.Mon;
int z = (int)Days.Sat;
Console.WriteLine("Sun = {0}", x);
Console.WriteLine("Mon = {0}", y);
Console.WriteLine("Sat = {0}", z);
}
}
Output:
Sun = 0
Mon = 1
Sat = 6
Explanation:
In this instance, we define an enumeration called Days that includes the days of the week starting from 0 as the default value. Within the main method, it maps Sun, Mon, and Sat to their corresponding integer representations and displays them. The result displayed will show: Sun = 0, Mon = 1, Sat = 6.
Enum Methods and Properties
There exist various techniques and attributes associated with Enum in C#. A few of these are outlined below:
1) GetValues in C#
In C# development, the Enum.GetValues method is used to fetch an array containing all the values defined within an enum data type.
In this C# Enum example, we demonstrate how to retrieve all values by utilizing the getValues method.
Let's consider a scenario to demonstrate how C# enum constants can be accessed by utilizing the getValues method.
Example
using System;
public class EnumExample
{
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
public static void Main()
{
foreach (Days d in Enum.GetValues(typeof(Days)))
{
Console.WriteLine(d);
}
}
}
Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
2) GetNames in C#
In C# development, the Enum.GetNames function is used to fetch an array containing all the names defined within an enumeration type.
Enumerations in C# provide a way to define a set of named constants. In this C# Enum example, we will demonstrate how to iterate through all the values of an enumeration using the GetNames method.
Let's consider a scenario to demonstrate how C# enum constants can be accessed by iterating through all values using the getValues method.
Example
using System;
public class EnumExample
{
public enum Days { Sun, Mon, Tue, Wed, Thu, Fri, Sat };
public static void Main()
{
foreach (string s in Enum.GetNames(typeof(Days)))
{
Console.WriteLine(s);
}
}
}
Output:
Sun
Mon
Tue
Wed
Thu
Fri
Sat
Explanation:
In this instance, we are working with an enum named Days that includes values from Sunday to Saturday. Within the main function, it fetches all the enum names as strings by utilizing Enum.GetNames and then proceeds to output each name individually using a foreach loop, showcasing all the days of the week.
3) IsDefined in C#
In C# programming, this function is utilized to verify if a provided value or name is present within a designated enumeration, yielding a Boolean outcome.
C# Enum.IsDefined Example
Let's consider a scenario to demonstrate the usage of the enum.IsDefined method in C#.
Example
using System;
public class EnumExample
{
public enum Colors {
Red,
Green,
Blue,
Yellow,
Black,
Orange
}
public static void Main()
{
Console.WriteLine(Enum.IsDefined(typeof(Colors), "Black")); // true
Console.WriteLine(Enum.IsDefined(typeof(Colors), "Pink")); // false
}
}
Output:
True
False
Converting Enums
In C# development, Enums serve as strongly-typed constants that allow explicit casting to and from underlying numeric types such as int, byte, and others. Enumerations can also be converted to strings and parsed back from strings into enum values. This functionality proves beneficial when dealing with user interfaces, file operations, or databases where enum names or values need to be displayed or stored.
C# Example for Converting Enums
Let us take an example to convert the Enum in C#.
Example
using System;
public class EnumExample
{
public enum Status { Off = 0, On = 1 }
public static void Main()
{
int val = (int)Status.On;
Console.WriteLine("Integer value: " + val);
Status s = (Status)0;
Console.WriteLine("Enum value: " + s);
string name = Status.On.ToString();
Console.WriteLine("String value: " + name);
Status parsed = (Status)Enum.Parse(typeof(Status), "Off");
Console.WriteLine("Parsed enum: " + parsed);
}
}
Output:
Integer value: 1
Enum value: Off
String value: On
Parsed enum: Off
Explanation:
In this instance, we establish an enumeration named Status with values Off=0 and On=1. This enumeration facilitates the conversion of an enum constant to its corresponding integer representation, casts an integer value back to the enum type, transforms an enum into a string by utilizing the ToString method, and interprets a string input to retrieve the associated enum value through the Enum.Parse method.
Enums in Switch Statements
In C# development, switch statements pair effectively with Enums. Incorporating an enum in a switch statement enables the execution of diverse actions based on the enum's value. This practice enhances the clarity and sustainability of code by eliminating hardcoded literals.
Syntax:
It has the following syntax:
enum Enumname { Val1, Val2, Val3 }
Enumname var = EnumName.Val2;
switch (var)
{
case EnumName.Val1:
// block of code
break;
case EnumName.Val2:
// block of code
break;
default:
// default code block
break;
}
C# Enum Example using Switch Statement
Let's consider a scenario to demonstrate the enum with a switch statement in C#.
Example
using System;
public class EnumSwitch
{
public enum Day { Sun, Mon, Tue, Wed, Thu, Fri, Sat }
public static void Main()
{
Day day= Day.Wed;
switch (day)
{
case Day.Sun:
Console.WriteLine("It's Sunday");
break;
case Day.Wed:
Console.WriteLine("Midweek day");
break;
case Day.Sat:
Console.WriteLine("Weekend!");
break;
default:
Console.WriteLine("A regular weekday");
break;
}
}
}
Output:
Midweek day
Explanation:
In this instance, we define an enumeration called Day that represents each day of the week. Within the main method, it sets the variable today to Wednesday and employs a switch statement to evaluate its value. The output "Midweek day" is displayed as the variable holds the value Day.Wed.
Specifying Enum Type in C#
The base data type for an enum in C# is integer, specifically a 32-bit signed integer to store each enum member. Alternatively, we have the flexibility to define other integral types like byte, sbyte, short, ushort, uint, long, or ulong based on memory requirements or compatibility with external data structures.
Syntax:
It has the following syntax:
enum EnumName : underlyingType
{
Value1,
Value2,
Value3
}
C# Enum Example to specify Enum Type
Let's consider an instance to define an Enum type in C#.
Example
using System;
enum TemperatureLevel : short
{
Low = -10,
Normal = 0,
Warm = 20,
Hot = 35,
Extreme = 50
}
class C# Tutorial
{
static void Main()
{
TemperatureLevel level = TemperatureLevel.Normal;
Console.WriteLine($"Temperature Level: {level}");
Console.WriteLine($"Underlying Value: {(short)level}");
TemperatureLevel extreme = (TemperatureLevel)50;
Console.WriteLine($"Casted from number: {extreme}");
}
}
Output:
Temperature Level: Normal
Underlying Value: 0
Casted from number: Extreme
Explanation:
In this illustration, we establish an enumeration named TemperatureLevel with short as the base type, allotting distinct numerical values to various temperature levels. Within the main routine, it assigns a level to Normal and displays both the enum's name and its corresponding value. Subsequently, it converts the integer 50 to the enum, representing the Extreme level, and showcases the result.
[Flags] Attribute for Bitwise Enums
In C#, applying the [Flags] attribute to an enum enables the representation of a set of bit fields. This feature permits the combination of enum values using bitwise operators, which is beneficial in scenarios involving multiple concurrent choices, permissions, or statuses.
C# Example to [Flags] Attribute for Bitwise Enum
Let's consider an example to demonstrate the flag attribute for a bitwise enumeration in C#.
Example
using System;
[Flags]
public enum A
{
None = 0,
Read = 1,
Write = 2,
Execute = 4
}
class C# Tutorial
{
static void Main()
{
A rights = A.Read | A.Write;
Console.WriteLine($"Assigned Rights: {rights}");
bool canWrite = rights.HasFlag(A.Write);
Console.WriteLine($"Has Write Permission: {canWrite}");
rights |= A.Execute;
Console.WriteLine($"Updated Rights: {rights}");
rights &= ~A.Read;
Console.WriteLine($"After Removing Read: {rights}");
if (rights == A.None)
Console.WriteLine("No permissions assigned.");
}
}
Output:
Assigned Rights: Read, Write
Has Write Permission: True
Updated Rights: Read, Write, Execute
After Removing Read: Write, Execute
Explanation:
In this illustration, we define an enum named A adorned with the [Flags] attribute to enable the amalgamation of multiple values through bitwise operations. Within the main method, permissions are allocated as Read | Write, resulting in an output of Read, Write. The code then checks for the presence of Write using HasFlag. Subsequently, the permission for execute is included, followed by the exclusion of read using a combination of bitwise AND and NOT. Finally, a check is performed to ascertain if there are no remaining permissions, and the output is displayed accordingly.
Conclusion
In summary, C# Enums offer a secure and aesthetically pleasing method of denoting a set number of named constants. They enhance clarity, eliminate mistakes stemming from hardcoded values, and integrate seamlessly with control structures like switch statements. By utilizing underlying types, applying attributes like standard [Flags], and incorporating extension methods, enums can be enhanced to achieve greater flexibility and strength.
C# Enum FAQs
1) What is an enum in C#?
An enum in C# represents a value type that specifies a collection of named constants. Utilizing enums improves code legibility and streamlines the manipulation of associated values.
The default underlying type for an enum in C# is int.
The underlying type for an enum is int by default. Nevertheless, it is possible to explicitly specify other integral types like byte, short, or long.
3) Can we assign specific values to enum members?
Yes, it is possible to assign custom numerical values to enum elements. This functionality proves beneficial when integrating with external platforms or APIs that demand precise values.
4) Can the enums contain duplicate values?
Yes, it is possible for multiple identifiers to share an identical value. Nevertheless, only the initial identifier is retrieved when transitioning from a value back to an identifier.
5) Are enums reference types or value types?
Enums represent a set of named constants and are based on the System.Enum class. They handle memory allocation and assignment in a similar way to other value types.