CSharp - Cast enum value to int


We create enumerations with the enum keyword.

Enum is the base class for all enumerations.

We can assign a set of integral named constants through enumeration.

The default integral type is System.Int32.


using System;
enum Values { val1, val2, val3, val4, val5 };
class Program//from  ww w .ja v a2 s  . co  m

    static void Main(string[] args)
        int x1 = (int)Values.val1;
        int x2 = (int)Values.val2;
        int x3 = (int)Values.val3;
        int x4 = (int)Values.val4;
        int x5 = (int)Values.val5;
        Console.WriteLine("x1={0}", x1);
        Console.WriteLine("x2={0}", x2);
        Console.WriteLine("x3={0}", x3);
        Console.WriteLine("x4={0}", x4);
        Console.WriteLine("x5={0}", x5);




By default, each member is taking an integer value.

The values for x1, x2, and x3 are automatically assigned.

These assignments started from 0 and incremented automatically by 1.

For example, x1 is containing 0, x2 is containing 1 and x3 is containing 2.

This increment is happening according to their declaration order.

Related Topic