The Basics of Enums in C#
Enums allow you to create a named set of values, making your code more expressive. For example:
public enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
Here, DaysOfWeek
is an enum representing the days of the week. Each day is assigned an integral value starting from 0 by default.
String to Enum Conversion
Converting a string to an enum involves parsing the string and matching it with the corresponding enum value. C# provides a method called Enum.Parse
for this purpose.
using System;
class Program
{
enum DaysOfWeek
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
static void Main()
{
string input = "Friday";
DaysOfWeek day = (DaysOfWeek)Enum.Parse(typeof(DaysOfWeek), input);
Console.WriteLine($"Converted string '{input}' to enum: {day}");
}
}
We converted the string "Friday" to the DaysOfWeek
enum in this program. The Enum.Parse
method takes the enum type and the string representation of the enum value, returning the corresponding enum value.
Output:
Converted string 'Friday' to enum: Friday
Comments (0)