Do you want to know about C#.Net enums? In this C#.Net tutorial, I will explain how to use enum in C#.Net with various examples.
Enums, short for enumerations, are distinct types provided by C# that comprise a set of named constants. They are useful for representing a collection of related named constants in a type-safe manner, making code easier to read and maintain. For example, instead of using integer constants for days of the week, an enum can define these as named members of an ‘Days’ enum, enhancing clarity and reducing the chance for errors.
In C#, the ‘enum’ keyword is used to define an enumeration type, which is a value type derived from the base class System.Enum. Once declared, enums increase code comprehensiveness and enforce compile-time checking of values, which helps avoid assigning invalid values in the code. This static typing prevents runtime errors and facilitates better code completion tools in integrated development environments (IDEs).
To demonstrate the practical use of enums in C#, this article provides a simple example: an enumeration representing user roles within an application. It illustrates how to define an enum, how to assign and use enum values, and how to parse string values into an enum.
Introduction to Enums in C#
Enums, or enumerations, in C# provide a type-safe way to work with sets of named constants.
Definition of Enums in C#
An enum in C# is a value type defined by a set of named constants of the underlying integral numeric type. By default, the associated constant values of enum members are of type int
and start at zero, incrementing by one for each subsequent member. For example:
enum DayOfWeek
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Advantages of Using Enums in C#
Enums offer several benefits:
- Type Safety: Enums provide compile-time checking of valid values, reducing errors from using invalid numbers.
- Code Clarity: Code that uses enums is more readable since it conveys the intent more clearly than using numbers.
- Ease of Maintenance: Enums centralize the definition of related constants, making updates simpler and less error-prone.
Declaring Enums in C#
In C#, enums are powerful enumerations that allow a programmer to define a set of named constants. Using enums can make code more readable and maintainable.
Basic Enum Declaration
To declare an enum, one uses the enum
keyword followed by the name of the enumeration. By default, the underlying type of each element in the enum is int
, and the first enumerator has the value 0
, with each subsequent enumerator increasing by 1
.
enum Days
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Specifying Underlying Types for Enums in C#
One can specify the underlying type of an enumeration to be any integral type by placing a colon after the enum name followed by the type. The common types used are byte
, sbyte
, short
, ushort
, int
, uint
, long
, or ulong
.
enum ErrorCode : byte
{
None,
Unknown,
ConnectionLost,
OutOfMemory
}
Assigning Values to Enum Members
It is possible to assign values to enum members during declaration manually. This can be useful for setting flags or integrating with external systems that use numeric codes.
enum Permissions
{
Read = 1,
Write = 2,
Execute = 4,
FullControl = Read | Write | Execute
}
How to Use C# Enums in Code
Enums in C# provide a way to work with sets of named integer constants, making code more readable and maintainable. They are strongly typed constants, which make the code less error-prone.
Accessing Enum Values
To access enum values, one typically references them by name through the enum type. For example, given an enum DaysOfWeek
, one can access Monday
using DaysOfWeek.Monday
.
enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
class Program
{
static void Main()
{
DaysOfWeek startDay = DaysOfWeek.Monday;
}
}
Enum Conversion and Casting
Enums in C# can be cast to their underlying integral types, and vice versa. By default, the underlying type is an int
, but this can be explicitly defined.
enum DaysOfWeek : byte { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
class Program
{
static void Main()
{
int dayIndex = (int)DaysOfWeek.Tuesday; // Casting enum to int
DaysOfWeek day = (DaysOfWeek)3; // Casting int to enum
}
}
Comparing Enum Values
Enum values can be compared using standard equality operators. However, when they represent flags, bitwise operators should be used for comparison.
enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
class Program
{
static void Main()
{
bool isMonday = DaysOfWeek.Monday == DaysOfWeek.Monday; // true
}
}
Best Practices to Use C# Enums
When implementing enumerated types in C#, adhering to established best practices ensures maintainability and clarity in code. These guidelines cover naming conventions and appropriate scenarios for using enums.
Naming Conventions
Enum members should be PascalCase
, which means the first letter of each word is capitalized. For example, consider an enum representing colors:
public enum Color
{
Red,
Green,
Blue
}
Enum types, as they represent a distinct set of named constants, should also be named in PascalCase
and be singular unless they represent a collection of flags, in which case they should be plural. For example:
[Flags]
public enum FileAccessPermissions
{
Read,
Write,
Execute,
ReadWrite = Read | Write
}
When to Use Enums
Enums should be used when a variable can take one out of a small set of possible values that are known at compile time. They make the code more readable and less error-prone. Use enums instead of constants to represent groups of related numeric values:
Use Case | Example |
---|---|
Representing states | enum ConnectionState { Disconnected, Connecting, Connected, Disconnecting } |
Categorizing entities | enum ProductType { Beverage, Food, Hardware } |
Defining options or modes | enum FileMode { CreateNew, OpenExisting, Append } |
Enums can also be used in switch
statements to make different execution paths clear:
switch(connectionState)
{
case ConnectionState.Disconnected:
Connect();
break;
case ConnectionState.Connected:
Disconnect();
break;
}
Practical Examples of Enums in C#
In C#, an enum
is a value type defined by a set of named constants of the underlying integral numeric type. To illustrate its use, consider a simple scenario where one needs to define a list of days in a week:
enum WeekDays
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Usage in a Program:
One can use the WeekDays
enum to perform operations based on days. In the following code, Today()
function returns the current day of the week as an enum
:
public WeekDays Today()
{
return WeekDays.Friday; // Assume it is Friday
}
Here is a complete C# code to use enums in C#.
using System;
namespace WeekDayEnumExample
{
class Program
{
// Define the WeekDays enum
enum WeekDays
{
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
static void Main(string[] args)
{
// Assign a value from the enum to a variable
WeekDays today = WeekDays.Wednesday;
// Output the current day using the enum value
Console.WriteLine("Today is " + today);
// Demonstrate getting the integer value of an enum
int dayNumber = (int)today;
Console.WriteLine("Day number of " + today + " is " + dayNumber);
// Demonstrate iterating over the enum values
Console.WriteLine("The days of the week are:");
foreach (WeekDays day in Enum.GetValues(typeof(WeekDays)))
{
Console.WriteLine(day);
}
}
}
}
Once you execute the code, you can see the output in the screenshot below. I have executed the code using a C#.Net console application.
Switch Case with Enum:
Enum values are often used in switch
statements to execute specific code blocks:
public void DisplayWeekendActivities(WeekDays day)
{
switch (day)
{
case WeekDays.Saturday:
case WeekDays.Sunday:
Console.WriteLine("Relax or go out with friends.");
break;
default:
Console.WriteLine("Continue with regular work.");
break;
}
}
In this code, the program outputs different activities based on whether the day is a weekday or a weekend.
Italics and Bold Usage: When declaring an enum
, the naming conventions should follow PascalCase, which means starting with a capital letter and capitalizing the first letter of subsequent concatenated words.
Conclusion
Enums in C# are powerful enumerations that allow for creating a set of named integer constants. This can make the code more readable, maintainable, and less prone to errors. Consider these key takeaways when working with enums:
- Enums enhance code clarity by allowing the use of descriptive names for sets of numeric values.
- They should be used when a variable can only take one out of a small set of possible values.
- Type safety is improved with enums as they prevent invalid values from being assigned to variables.
When implementing enums, developers should:
- Clearly define the enum at the namespace level for accessibility.
- Use the
enum
keyword followed by the name and the underlying type, if not defaulting toint
. - Prefer
ToString()
for displaying enum names, andEnum.Parse()
orEnum.TryParse()
for converting strings to enum values. - Utilize
FlagsAttribute
for bitwise operations if multiple enum values can be combined.
In this C# tutorial, I have explained how to use enums in C#.net with various examples.
You may also like:
Bijay Kumar is a renowned software engineer, accomplished author, and distinguished Microsoft Most Valuable Professional (MVP) specializing in SharePoint. With a rich professional background spanning over 15 years, Bijay has established himself as an authority in the field of information technology. He possesses unparalleled expertise in multiple programming languages and technologies such as ASP.NET, ASP.NET MVC, C#.NET, and SharePoint, which has enabled him to develop innovative and cutting-edge solutions for clients across the globe. Read more…