Home > Backend Development > C++ > How Can I Retrieve an Enum Value Using Its Description in C#?

How Can I Retrieve an Enum Value Using Its Description in C#?

Mary-Kate Olsen
Release: 2025-01-21 21:21:10
Original
352 people have browsed it

How Can I Retrieve an Enum Value Using Its Description in C#?

Enhancing C# Enums: Retrieving Values by Description

This article demonstrates a powerful technique to improve the functionality of C# enums. We'll focus on efficiently retrieving an enum value using its description attribute. This approach offers increased flexibility and simplifies code development.

The solution involves a static helper class, EnumEx, containing a generic method: GetValueFromDescription. This method accepts a description string and the enum type as input. It then iterates through the enum's fields, using reflection to find the DescriptionAttribute. If a match is found between the attribute's description and the input string, the corresponding enum value is returned.

If no DescriptionAttribute is present, the method falls back to comparing the field name with the input description. If a match is found here, the corresponding enum value is returned. Otherwise, an ArgumentException is thrown (or the default enum value is returned, depending on implementation preference).

This method allows for straightforward retrieval of enum values using descriptions:

var panda = EnumEx.GetValueFromDescription<animal>("Giant Panda");
Copy after login

This extension significantly improves code maintainability and readability by offering a cleaner way to access enum values based on their descriptions.

The above is the detailed content of How Can I Retrieve an Enum Value Using Its Description in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template