Enums in C# are ideal for representing a fixed set of related constants. However, data often comes from external sources like user input, configuration files, or APIs. In such cases, the values might be in int
or string
format. To use them as enums, conversion is required.
Here is how to safely convert a string or an integer into an enum.
🎯 Define the Enum Type
Start by defining your enum. For example:
public enum Days
{
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6,
Sunday = 7
}
🔢 Convert from int
to Enum
If you are working with numeric values, you can cast the integer directly:
Days value = (Days)1; // value = Days.Monday
This approach is fast, but keep in mind that casting an invalid number does not throw an error. Instead, it returns the numeric value, even if it does not correspond to a defined enum member.
You can check validity first using Enum.IsDefined
:
if (Enum.IsDefined(typeof(Days), 3))
{
Days value = (Days)3;
// value = Days.Wednesday
}
🔤 Convert from string
to Enum
To convert a string to its corresponding enum, use the Enum.Parse
method:
Days value = (Days)Enum.Parse(typeof(Days), "Friday");
If the string is not a valid enum name, this will throw an exception. You can prevent this with a try-catch block:
try
{
Days value = (Days)Enum.Parse(typeof(Days), "Funday");
}
catch (ArgumentException)
{
// Handle invalid value
}
Or use Enum.TryParse
for a cleaner and safer approach:
if (Enum.TryParse("Friday", out Days value))
{
// value is Days.Friday
}
You can also make it case-insensitive:
Enum.TryParse("friday", true, out Days value);
✅ Best Practices
Use
Enum.TryParse
instead ofEnum.Parse
to avoid exceptionsUse
Enum.IsDefined
when converting from integers to validate the valueHandle unexpected values gracefully, especially with user input or external data
Final Tip:
Enums make your code easier to read and maintain. Converting values to enums the right way ensures your application behaves predictably and safely, even with unexpected input.