Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Value of an Enum

Tags:

c#

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?

like image 754
sl3dg3 Avatar asked Nov 28 '22 22:11

sl3dg3


2 Answers

I don't know, what you mean by "Enum-Code", but why not just convert it to an int?

int value = (int)MyEnum.MyEnumCode;
like image 79
Daniel Hilgarth Avatar answered Nov 30 '22 11:11

Daniel Hilgarth


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.

like image 43
Cine Avatar answered Nov 30 '22 11:11

Cine