Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nice way to get names and their enum values in C#

Tags:

c#

enums

I want do achieve a pretty simple task, but the thing is to do this in a nice, simple way. We all want to write pretty code that is easy to maintain, quick to understand. I have a problem that experienced C# developers may help me with.

I want to create a dictionary, where keys (string[]) are names of enum values and values are their ecorresponding enum values. If this is confusing, let me give you a short example:

enum Animals
{
    Dog,
    Cat,
    Fish
}

Dictionary<string, Animals> result = new Dictionary<string, Animals>()
{
    { "Dog", Animals.Dog },
    { "Cat", Animals.Cat },
    { "Fish", Animals.Fish }
};

Here is my approach:

a little extension:

public static IEnumerable<T> GetValues<T>() => Enum.GetValues(typeof(T)).Cast<T>();

and then the construction:

var result = Utils
     .GetValues<Animals>()
     .ToDictionary(x => x.ToString(), x => x);

How would you, experienced devs, approach this problem to write it in a clearer way? Or perhaps there is a trick with enums that would enable a quick lookup like "give me an enum which name satisfies my condition".

like image 275
Patryk Golebiowski Avatar asked Jan 31 '26 23:01

Patryk Golebiowski


2 Answers

To take a string and convert it to its matching enum value, or even fail if there is no matching enum value you should use Enum.TryParse:

Animals animal;
if (Enum.TryParse("Dog", out animal))
    // animal now contains Animals.Dog
else
    // animal "undefined", there was no matching enum value
like image 78
Lasse V. Karlsen Avatar answered Feb 03 '26 13:02

Lasse V. Karlsen


The Parse method of the Enum type is what I think you are looking for.

 var value = Enum.Parse(typeof(T), "Dog");
like image 37
Kratz Avatar answered Feb 03 '26 13:02

Kratz