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
- .NET (10)
- Apple (2)
- Business (5)
- CSS (1)
- HTML (2)
- Innovation (4)
- Java (4)
- Javascript (1)
- Leadership (1)
- MySQL (2)
- Oracle (6)
- Postgres (1)
- Programming (5)
- Rails (4)
- Ruby (10)
- SQL Server (9)
- Subversion (1)
- Web (5)
- Windows Server (2)
Archives
- July 2010 (2)
- September 2009 (5)
- August 2009 (1)
- July 2009 (12)
- June 2009 (16)
- May 2009 (3)