How to get an Enum from a String in C#
By FoxLearn 12/26/2024 7:41:57 AM 151
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.
- Using the OrderBy and OrderByDescending in LINQ
- Querying with LINQ
- Optimizing Performance with Compiled Queries in LINQ
- MinBy() and MaxBy() Extension Methods in .NET
- SortBy, FilterBy, and CombineBy in NET 9
- Exploring Hybrid Caching in .NET 9.0
- Using Entity Framework with IDbContext in .NET 9.0
- Primitive types in C#
Categories
Popular Posts
Motiv MUI React Admin Dashboard Template
11/19/2024
AdminKit Bootstrap 5 HTML5 UI Kits Template
11/17/2024
K-WD Tailwind CSS Admin Dashboard Template
11/17/2024