Basic C#: Converting a string to a proper Enum value

Posted by Adrian Tue, 07 Jul 2009 15:52:00 GMT

This is a very quick beginners tip for those learning .NET. In it, I show you how you can convert between strings, which might be loaded from configuration files or user input, and Enums, that you use to define constants in your application.

First of all, here's a sample enum:

enum Animal { Monkey, Fish, Spider, Pig, Goat }

As you probably know, we use enums like this:

Animal a = Animal.Pig

if (a == Animal.Pig) Oink();

That's a rubbish example, but you get the idea. What if we have the string "Pig", and we need to set our variable based on that? A big if or switch statement would work, but that would add serious maintenance overhead to your application. Instead, we can use Enum.Parse():

Animal a = (Animal)Enum.Parse(typeof(Animal), "Fish");

Enum.Parse returns an object, so we must cast it appropriately. Note also the typeof() first parameter, telling Enum.Parse the type of string it will be trying to decode.

You can also go the other way using just ToString:

Animal a = Animal.Spider

string result = a.ToString(); // result == "Spider"

About

We are a small British company that produces business-oriented software and solutions. These articles are a product of our daily work - information that we think might be useful to share. We hope you find them useful.

Our Software

These are some of our products. Several are open source, some are web-based and others are proprietary:

Categories

Archives

Syndicate

ml> ._trackPageview(); } catch(err) {} ml> l> pageTracker._trackPageview(); } catch(err) {} ml> ._trackPageview(); } catch(err) {} ml> l>