How to get int value from enum in C#?


Firstly, set the enum −

public enum Vehicle { Car, Bus, Truck }

Now use typecasting to cast an enum to int −

int a = (int)Vehicle.Car;

The following is the complete code to cast an enum to int −

Example

 Live Demo

using System;

public class Demo {
   public enum Vehicle { Car, Bus, Truck }

   public static void Main() {
      int a = (int)Vehicle.Car;
      int b = (int)Vehicle.Bus;
      int c = (int)Vehicle.Truck;

      Console.WriteLine("Car = {0}", a);
      Console.WriteLine("Bus = {0}", b);
      Console.WriteLine("Truck = {0}", c);
   }
}

Output

Car = 0
Bus = 1
Truck = 2

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 20-Jun-2020

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements