Enum with Customized Value in C#

CsharpProgrammingServer Side Programming

Enum is Enumeration to store a set of named constants like year, product, month, season, etc.

The default value of Enum constants starts from 0 and increments. It has fixed set of constants and can be traversed easily. However you can still change the start index and customize it with the value of your choice.

In the following example, I have set the customized value to be 20 instead of the default 0.

Example

 Live Demo

using System;
public class Demo {
   public enum Vehicle { Car =20, Motorcycle, Bus, Truck }
   public static void Main() {
      int a = (int)Vehicle.Car;
      int b = (int)Vehicle.Motorcycle;
      int c = (int)Vehicle.Bus;
      int d = (int)Vehicle.Truck;
      Console.WriteLine("Car = {0}", a);
      Console.WriteLine("Motorcycle = {0}", b);
      Console.WriteLine("Bus = {0}", c);
      Console.WriteLine("Truck = {0}", d);
   }
}

Output

Car = 20
Motorcycle = 21
Bus = 22
Truck = 23
raja
Updated on 23-Jun-2020 09:29:44

Advertisements