Sunday, January 30, 2011

String To Enum Conversion In C#

In the XNA project I'm currently working on, many of the animations have a state for each cardinal direction. This information is stored in XML as a string (NE/NW/SE/SW). However, in the code it's convenient to store this information as an Enum like so:


public enum Facing {
    NE, SE, SW, NW
}

In order to determine which state of the animation to use, it becomes necessary to convert between the Enum and the string in the XML file. Fortunately, there's a handy function Enum.Parse that makes this really easy:

Facing enumValue = Enum.Parse(typeof(Facing), directionString);

Very handy. I haven't really used enums before but they're becoming a very useful tool.

No comments:

Post a Comment