This is a common task for C# programmers. You have a string value and need to convert it to the equivalent Enum value. Piece o’ cake: code some nifty switch
statement or maybe a bunch of if / else
conditions to test for every possible match, right? … er, NO.
Say you have declared an Enum like:
public enum FeedBackMessageType { None = 0, Success, Warning, Error }
Then you should be able to convert a string like:
var feedbackMessageType = (FeedBackMessageType) Enum.Parse(typeof(FeedBackMessageType), "Success", true);
If you are trying to convert a string that doesn’t match any of values from the enum, you will get a ArgumentException. How to avoid this? Try:
var invalidMessageType = "Info"; var feedbackMessageType = Enum.IsDefined(typeof(FeedBackMessageType), invalidMessageType) ? (FeedBackMessageType) Enum.Parse(typeof(FeedBackMessageType), invalidMessageType , true) : FeedBackMessageType.None;
One caveat, the IsDefined
method has no ignore case
parameter. According to MSDN: The characters in the string must have the same case as the enumeration member name.
References: