Reputation: 5180
I'm little bit confused: Is this really the only method to read a value from an Enum-Code?
(int)Enum.Parse(typeof(MyEnum), MyEnumCode.ToString())
Something such essential and no better way to get the value?
Upvotes: 4
Views: 563
Reputation: 4392
No, you can just cast to int directly:
(int)MyEnum.MyEnumCode
Elaborating a bit. Internally an enum is actually an int. Therefore the cast is free. But it also means that you can easily have values in your enum that doesn't exist. E.g.
MyEnum val = (MyEnum)-123544;
Is perfectly valid code.
Upvotes: 7
Reputation: 5043
What is it you want to achieve? Do you want the integer value associated with an enum? You can just cast the enum to int...
(int)MyEnum.MyEnumCode;
Upvotes: 2
Reputation: 60684
What about
(int)MyEnumCode?
The underlying type for enum is int by default, so you can simply cast it.
Upvotes: 1
Reputation: 11734
Try this:
int x = MyEnumCode as int;
string y = MyEnumCode.ToString();
int z = (int)MyEnumCode;
Upvotes: 1
Reputation: 174289
I don't know, what you mean by "Enum-Code", but why not just convert it to an int?
int value = (int)MyEnum.MyEnumCode;
Upvotes: 15