Skip to content

A more robust way of converting a string to an enumerated value (enum)

A while back, I had blogged about a tip that Mark Wagner had posted about converting a string to an enumerated value.  Tim Sneath posted a similar tip even earlier, except his had some additional error logging.  Tim’s post made it to DotNetKicks, which is good because having the additional error handling is just good coding practice. 

enum Sushi
{
Ika,
Hirameh,
Tako
}

// ...
Sushi lunch = (Sushi) Enum.Parse(typeof(Colour), "Tako", true);
Console.WriteLine("Sushi Value: {0}", lunch.ToString());

// To avoid an ArgumentException for strings that do have
// corresponding enumerate values, call Enum.IsDefined()
// first.

string NotSushi = "pizza";

if (Enum.IsDefined(typeof(Sushi), NotSushi))
{
lunch = (Sushi) Enum.Parse(typeof(Sushi), NotSushi, true);
}
else
{
// Add your error logic here
}

Mucho gracias to Tim & Mark…