Reputation: 353
I have defined a Enum as blow, it includes int type and character type.
I tried to parse string into enum, but it would occur error when input character.
How to fix this?
//parse successfully.
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "1");
//error:Requested value 'A' was not found.
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "A");
public enum MyEnum
{
[Description("Des1")]
Status1 = 1,
[Description("Des2")]
Status2 = 2,
[Description("Des3")]
Status3 = 3,
[Description("Des4")]
Status4 = 4,
[Description("Des7")]
Status5 = 5,
[Description("Des6")]
Status6 = 6,
[Description("Des7")]
Status7 = 7,
[Description("Des8")]
Status8 = 8,
[Description("Des9")]
Status9 = 9,
[Description("DesA")]
StatusA = 'A',
[Description("DesB")]
StatusB = 'B',
[Description("DesC")]
StatusC = 'C',
}
Update:
OK, I think I need check the input is digit or not to do different process. Code as Below did work, thanks for everyone's advise.
string inputParam = "A";
int useLess;
MyEnum myEnum;
var isDigit = int.TryParse(inputParam, out useLess);
if (isDigit) {
myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), inputParam);
}
else
{
myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), ((int)Convert.ToChar(inputParam)).ToString());
}
Upvotes: 2
Views: 118
Reputation: 271810
Enum.Parse
only works for the names or the numeric values of the associated constant values. of the enum members. 'A'
is neither of those. If you have passed the string "65"
to the method, it would have worked.
Note that how you write the associated constant value doesn't matter - whether it's 'A'
, or 65
, or 0b1000001
or 0x41
, they all look the same to the compiler. Enum.Parse
only accepts the second way of writing it.
To convert the character 'A'
to the enum type MyEnum
, you just need a cast:
MyEnum foo = (MyEnum)'A';
However, since you have a string "A"
here, you need to get the first character (assuming that you are sure that the string represents one of the associated constant values):
MyEnum foo = (MyEnum)"A"[0];
Upvotes: 2
Reputation: 109597
The issue here is that the enum is in fact based on int
values, so the char values are being converted to int
.
In other words, this:
StatusA = 'A',
Is actually converted to this:
StatusA = 65,
Because the actual numeric value of StatusA
is 65
, you'd have to do:
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "65");
or alternatively, to make it more obvious that 65
is 'A'
:
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), ((int)'A').ToString());
Note that enum.Parse()
will parse either the name of the enum member, or a string containing the numeric value of the enum member, so either "65" or "StatusA" would work.
So all of the following lines will return the same result:
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "65");
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), ((int)'A').ToString());
MyEnum myEnum = (MyEnum)Enum.Parse(typeof(MyEnum), "StatusA");
Upvotes: 3