Let's say I have an enum:
public enum MyEnum
{
OptionOne = 0,
OptionTwo = 2,
OptionThree = 4
}
Like it was said in the How should I convert a string to an enum in C#? question, I parse enum from string, using Enum.Parse
method:
public class Enumer
{
public static MyEnum? ParseEnum(string input)
{
try
{
return (MyEnum) Enum.Parse(typeof (MyEnum), input);
}
catch (ArgumentException)
{
return null;
}
}
}
Unfortunately, it doesn't work as expected with integer numbers, represented as strings.
I do not expect Parse.Enum() to convert int from string, but actually it does.
A simple test:
[TestClass]
public class Tester
{
[TestMethod]
public void TestEnum()
{
Assert.AreEqual(MyEnum.OptionTwo, Enumer.ParseEnum("OptionTwo"));
Assert.IsNull(Enumer.ParseEnum("WrongString"));
Assert.IsNull(Enumer.ParseEnum("2")); // returns 2 instead of null
Assert.IsNull(Enumer.ParseEnum("12345")); // returns 12345 instead of null
}
}
Only two checks of four can be passed.
Enumer.ParseEnum("2")
returns MyEnum.OptionTwo
instead of null
.
Moreover, Enumer.ParseEnum("12345")
returns 12345, regardless it's out of the scope.
What is the best way to parse:
- Only string values of "MyEnum.OptionOne", "MyEnum.OptionTwo", "MyEnum.OptionThree" into their enum counterparts.
- Strings "MyEnum.OptionOne", "MyEnum.OptionTwo", "MyEnum.OptionThree" AND the values of 0, 2 and 4 into MyEnum.OptionOne, MyEnum.OptionTwo, MyEnum.OptionThree respectively?
The link to the similar question How should I convert a string to an enum in C#? doesn't help with the test provided - it still converts strings as integers, even when they are out of the enum scope.