Let's say I have an enumeration:
public enum MyEnum
{
OptionOne = 0,
OptionTwo = 2,
OptionThree = 4
}
As said in How do I convert a string to an enumeration question in C #? I am parsing an enumeration from a string using a method Enum.Parse:
public class Enumer
{
public static MyEnum? ParseEnum(string input)
{
try
{
return (MyEnum) Enum.Parse(typeof (MyEnum), input);
}
catch (ArgumentException)
{
return null;
}
}
}
Unfortunately, it does not work as expected with integers represented as strings.
I do not expect Parse.Enum () to convert an int from a string, but it actually 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"));
Assert.IsNull(Enumer.ParseEnum("12345"));
}
}
Only two out of four checks can be completed.
Enumer.ParseEnum("2")returns MyEnum.OptionTwoinstead null.
Also Enumer.ParseEnum("12345")returns 12345, regardless of scope.
What is the best way to analyze:
- "MyEnum.OptionOne", "MyEnum.OptionTwo", "MyEnum.OptionThree" .
- "MyEnum.OptionOne", "MyEnum.OptionTwo", "MyEnum.OptionThree" 0, 2 4 MyEnum.OptionOne, MyEnum.OptionTwo, MyEnum.OptionThree ?
#? - , .