Converting a String into an Enum Variable and Vise Versa

Sometimes you come across situations when you would want to convert an enum variable to a string. For instance, you might want to store it in a database as a string. This is, of course, very easy to do, given that enum is the same thing as Enum class which, having inherited ToString() method, will return you exactly what you see on your screen:

public enum TimeOfDay
var timeOfDay = TimeOfDay.Morning;
var s = timeOfDay.ToString();    // will return a string "Morning"
s = timeOfDay + "";    // will return a string "Morning" as it will call ToString() on timeOfDay because the second parameter in the operator is a string

Now, what if you want to get back from a string?
Well, remember that enum is a class and can have all features of such. Two of the most common methods of classes that represent types are Parse() and TryParse(). Assuming we “know” we can match a string to a literal enum member, we can simply do:

var time = (TimeOfDay)Enum.Parse(typeof(TimeOfDay), "Evening");

Now, there is a third optional parameter you can pass, indicating whether the match should be case-sensitive.
Now, what happens if your string does not match any of your defined members of enum? Well, you’ll get an exception thrown. You can avoid it by checking for whether a member of enum exists beforehand:

if (Enum.IsDefined(typeof(TimeOfDay), "Value That Does not Exist"))
    // do something here because the string does not correspond to an enum member

I hope this helps understanding how enum’s work in .NET, being not just sets but rather classes, and how one can easily integrate them with other components of modern applications.

This entry was posted in C# and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *