CSharp - enum value storage type

Introduction

Can we specify an alternative integral type to an enum like this?

enum Values :byte{ val1 , val2, val3 };

Yes, it is perfect.

Will the code compile?

enum simpleColors : string
{
    red, green, yellow,black, blue,pink
};

No. Only sbyte, short, ushort, int, uint, long, and ulong are allowed.

We can check the default storage type of an enum?

Demo

using System;
class Program//from w  ww .  j a  v  a  2s. c o  m
{
    enum Values { val1, val2 = 26, val3 = 12, val4, val5 };
    enum TrafficLight : byte
    {
        red, green = (int)Values.val3, yellow
    };
    static void Main(string[] args)
    {
        Console.WriteLine("Default  Storage type of Values is {0}", Enum.GetUnderlyingType(typeof(Values)));//System.Int32
        Console.WriteLine("Default  Storage type of TrafficLight is {0}", Enum.GetUnderlyingType(typeof(TrafficLight)));//System.Byte
    }
}

Result

Related Topic