Question

I have a dictionary that looks like this:

var myDictionary = new Dictionary<Fruits, Colors>();

Fruits and Colors are enumerations:

public enum Fruits
{
    Apple,
    Banana,
    Orange
}

public enum Colors
{
    Red,
    Yellow,
    Orange
}

I'm attempting to build this dictionary from a plain text file at run time, so I need to do be able to do something like this:

private addFruit( string fruit, string color )
{
    myDictionary.Add( Fruits[fruit], Colors[color] );
}

That doesn't work obviously but neither do any of these:

myDictionary.Add( fruit, color );
myDictionary.Add( new KeyValuePair<Fruits, Colors>( fruit, color ) );
myDictionary.Add( new KeyValuePair<Fruits, Colors>( Fruits[fruit], Colors[color] ) );

Is there any way to do this?

Was it helpful?

Solution

You need to parse the string values into the enum values using Enum.Parse:

private addFruit( string fruit, string color )
{
    Fruits parsedFruit = (Fruits) Enum.Parse(typeof(Fruits), fruit);
    Colors parsedColor = (Colors) Enum.Parse(typeof(Colors), color);
    myDictionary.Add(parsedFruit, parsedColor);
}

This will throw an error if the string value does not match any of the enum values (i.e. it is null, empty or a string that isn't in the enum).

In .Net 4.5, there is a TryParse method that may be more appropriate than just Parse.

OTHER TIPS

I believe you need something more like;

 myDictionary.Add(Fruits.Apple, Colors.Red);

If you have strings like "Apple" and "Red" and want to achieve the same you can use Enum.Parse like so;

 myDictionary.Add(Enum.Parse(typeof(Fruits), fruit), Enum.Parse(typeof(Color), color));

This of course has the potential to throw so in reality it would probably be better to use Enum.TryParse outside of the Add call then after the input strings are validated do the actual call to Add.

You need to parse the string value into a Fruit/Color value.

You can accomplish this with Enum.Parse, or even better in .NET Framework 4+ Enum.TryParse<TEnum>.

Make sure you cast your result when using Enum.Parse, as it will return an Object.

var stringValue = "Apple";
(Fruit)Enum.Parse(typeof(Fruit), stringValue);

I have in the past created a generic extension method on string to accomplish enum parsing in a more friendly manner.

public static class StringExtensions
{
    public static bool TryParse<TEnum>(this string toParse, out TEnum output)
        where TEnum : struct
    {
        return Enum.TryParse<TEnum>(toParse, out output);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top