Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

enum
c#
communitycreator

How to cast an enum to int in C#

Programming Bytes

Overview

To convert an enum to int, we can:

  1. Typecast the enum value to int.
  2. Use the ToInt32 method of the Convert class.

Example

The below code demonstrates how to cast an enum to int:

using System;
					
public class EnumTest {
	enum Result {
    	Fail,
		Pass
	};
	
	public static void Main() {
		Console.WriteLine(Result.Pass);
		int passIntVal = (int) Result.Pass;
		Console.WriteLine("The int value of Pass is " + passIntVal);

		int failIntVal = Convert.ToInt32(Result.Fail);
		Console.WriteLine("The int value of Fail is " + failIntVal);
	}
}
Converting enum value to int value

Explanation

Let’s break down the code written above:

  • Lines 4 to 7: We create an enum object Result with two values, Fail and Pass. The default underlying data type for an enum is int . So the value of Fail is 0 and the value of Pass is 1.
  • Line 11: We use type casting to convert the Result.Pass enum into an int. This returns the respective int value of the enum.
  • Line 14: We use the ToInt32 method of the Convert class to convert the enum value Result.Fail to an int value. This method returns 0 as a result.

 

.

RELATED TAGS

enum
c#
communitycreator
RELATED COURSES

View all Courses

Keep Exploring