Thursday, November 5, 2009

Parsing a string into an enumeration in C#

Sometimes we may need to convert a string value into a corresponding enumeration in C#. In such situations, this post comes in handy.

For example, if there an enumeration named States as follows in C#.

public enum States
     Virginia = 1,
     California = 2

//The following private function in your code can be reused across.
 private T Parse<T>(string value)
            return (T)Enum.Parse(typeof(T), value);

//Given a string "Virginia" this codes returns an enumeration
States objStates;
objStates = Parse<states>("Virginia");

No comments:

Post a Comment