C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In C#, an enumeration (or enum
) is a value type that represents a distinct set of named constants. Enums are useful when you need to represent a set of related values as named constants, making your code more readable and maintainable. In this tutorial, we'll cover the basics of using enums in C#.
To define an enum, use the enum
keyword followed by the name of the enumeration and a set of named constants enclosed in curly braces:
public enum DaysOfWeek { Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday }
By default, the underlying type of an enum is int
, and the constants are assigned integer values starting from 0. You can also explicitly specify the underlying type and assign custom values to the constants:
public enum DaysOfWeek : byte { Sunday = 0, Monday = 1, Tuesday = 2, // ... }
To use an enum, declare a variable of the enum type and assign one of its constants:
DaysOfWeek today = DaysOfWeek.Monday;
You can also use enums in switch statements, comparisons, and method parameters:
public static void PrintGreeting(DaysOfWeek day) { switch (day) { case DaysOfWeek.Sunday: Console.WriteLine("Happy Sunday!"); break; case DaysOfWeek.Monday: Console.WriteLine("Happy Monday!"); break; // ... } } DaysOfWeek today = DaysOfWeek.Monday; PrintGreeting(today);
You can convert an enum value to a string using the ToString()
method or to its underlying integer value using an explicit cast:
DaysOfWeek day = DaysOfWeek.Monday; string dayString = day.ToString(); // "Monday" int dayInt = (int)day; // 1
To convert a string or an integer to an enum value, you can use the Enum.Parse()
or Enum.TryParse()
methods and an explicit cast:
string dayString = "Monday"; DaysOfWeek day; if (Enum.TryParse(dayString, out day)) { Console.WriteLine("Parsed successfully: " + day); } else { Console.WriteLine("Failed to parse."); } int dayInt = 1; day = (DaysOfWeek)dayInt; // DaysOfWeek.Monday
In this tutorial, we've covered the basics of using enums in C#, including defining, using, and converting enums. Enums are a valuable tool for representing sets of related named constants, improving the readability and maintainability of your code.
C# enum examples:
using System; public enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } class Program { static void Main() { DaysOfWeek today = DaysOfWeek.Wednesday; Console.WriteLine($"Today is: {today}"); } }
Enum in C# with switch statement:
using System; public enum Season { Spring, Summer, Autumn, Winter } class Program { static void Main() { Season currentSeason = Season.Summer; switch (currentSeason) { case Season.Spring: Console.WriteLine("It's Spring!"); break; case Season.Summer: Console.WriteLine("It's Summer!"); break; // Handle other seasons... } } }
C# flags attribute enum:
Flags
attribute allows an enum to be treated as bit fields, enabling bitwise operations.using System; [Flags] public enum Permissions { Read = 1, Write = 2, Execute = 4 } class Program { static void Main() { Permissions userPermissions = Permissions.Read | Permissions.Write; Console.WriteLine($"User has Read and Write permissions: {userPermissions.HasFlag(Permissions.Read | Permissions.Write)}"); } }
C# enum underlying type:
int
), which specifies the storage format of the enum's values.using System; public enum Status : byte { Active, Inactive } class Program { static void Main() { Status userStatus = Status.Active; Console.WriteLine($"User status: {userStatus}"); } }
C# enum parsing and formatting:
Enum.Parse
and Enum.Format
methods.using System; public enum Colors { Red, Blue, Green } class Program { static void Main() { string colorString = "Blue"; Colors parsedColor = (Colors)Enum.Parse(typeof(Colors), colorString); Console.WriteLine($"Parsed Color: {parsedColor}"); string formattedColor = Enum.Format(typeof(Colors), Colors.Green, "G"); Console.WriteLine($"Formatted Color: {formattedColor}"); } }
C# enum to string:
ToString
method.using System; public enum Sizes { Small, Medium, Large } class Program { static void Main() { Sizes size = Sizes.Medium; Console.WriteLine($"Size: {size.ToString()}"); } }
Enum.TryParse in C#:
Enum.TryParse
is a safer way to parse strings into enums, avoiding exceptions for invalid values.using System; public enum Months { January, February, March } class Program { static void Main() { string monthString = "February"; if (Enum.TryParse(monthString, out Months parsedMonth)) { Console.WriteLine($"Parsed Month: {parsedMonth}"); } else { Console.WriteLine("Invalid month string"); } } }
C# enum to int conversion:
int
).using System; public enum Grades { A = 90, B = 80, C = 70 } class Program { static void Main() { Grades studentGrade = Grades.B; int gradeValue = (int)studentGrade; Console.WriteLine($"Grade Value: {gradeValue}"); } }