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

I want to achieve a fairly simple task, but the point is to do it in a nice, simple way. We all want to write beautiful code that is easy to maintain, quickly understand. I have a problem experienced C # developers might face.

I want to create dictionary

where keys

( string[]

) are names enum values

and values

are their respective 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's my approach:

small 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 do you experienced developers approach this problem to write it more clearly? Or maybe there is an enumeration trick that allows a quick lookup like " give me an enum whose name matches my condition ."

+3


source to share


2 answers


To take a string and convert it to the appropriate enum value, or even fail if there is no matching enum value, you must 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

      

+3


source


The Parse

type method Enum

is what I think you are looking for.



 var value = Enum.Parse(typeof(T), "Dog");

      

+2


source







All Articles