How to get an Enum from a String in C#
By FoxLearn 12/26/2024 7:41:57 AM 83
In this tutorial, we’ll demonstrate how to convert an enum from a string value in C#.
First, We will create a generic method to handle the conversion. This method will allow us to convert any enum type from a string, simplifying the process.
public static T StringToEnum<T>(string name) { return (T)Enum.Parse(typeof(T), name); }
With the Enum.Parse
method, we can easily convert a string to an enum value. Since Parse
returns an object, we need to cast it to the desired enum type.
For example:
public enum Seasons { Spring, Summer, Fall, Winter } public enum Colors { Red, Blue, Green, Yellow, Black, White }
Converting from a string to an enum
Seasons season = StringToEnum<Seasons>("Summer"); // season is now Seasons.Summer Colors color = StringToEnum<Colors>("Red"); // color is now Colors.Red
Handling an invalid string
What happens if we try to convert a string that doesn’t exist in the enum?
In that case, Enum.Parse
will throw an ArgumentException
.
Seasons season = StringToEnum<Seasons>("Autumn"); // Throws ArgumentException // Requested value "Autumn" was not found.
To avoid the exception, we can first check if the string is a valid enum value using Enum.IsDefined
. This method verifies if the provided string matches any of the enum names.
if (Enum.IsDefined(typeof(Seasons), "Autumn")) { StringToEnum<Seasons>("Autumn"); } else { Console.WriteLine("Invalid enum value."); } // Output: Invalid enum value.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#
Categories
Popular Posts
Freedash bootstrap lite
11/13/2024
Dashboardkit Bootstrap
11/13/2024
Material Lite Admin Template
11/14/2024
Stisla Admin Dashboard Template
11/18/2024