Converting enum to int in C#
Converting enum to int in C#
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
18-Aug-2023There are two ways to convert an enum to an int in C#:
ToInt()
method.value
property.Using the
ToInt()
methodThe
ToInt()
method takes an enum as its parameter and returns the corresponding integer value. The following code converts an enum to an int:C#
In this code, the
ToInt()
method is used to convert theColor.Red
enum to an int. The result is the integer value 0, which is the underlying value of theColor.Red
enum.Using the
value
propertyThe
value
property of an enum returns the underlying integer value of the enum. The following code also converts an enum to an int:C#
In this code, the
value
property of theColor.Red
enum is used to get the underlying integer value, which is 0.Which method you use to convert an enum to an int depends on your preference. The
ToInt()
method is more explicit, as it explicitly specifies that you are converting the enum to an int. However, thevalue
property is more concise and easier to read.