Why we can't have "char" enum types

I know this is an older question, but this information would have been helpful to me:

It appears that there is no problem using char as the value type for enums in C# .NET 4.0 (possibly even 3.5, but I haven't tested this). Here's what I've done, and it completely works:

public enum PayCode {
    NotPaid = 'N',
    Paid = 'P'
}

Convert Enum to char:

PayCode enumPC = PayCode.NotPaid;
char charPC = (char)enumPC; // charPC == 'N'

Convert char to Enum:

char charPC = 'P';
if (Enum.IsDefined(typeof(PayCode), (int)charPC)) { // check if charPC is a valid value
    PayCode enumPC = (PayCode)charPC; // enumPC == PayCode.Paid
}

Works like a charm, just as you would expect from the char type!


The default type is int. More information at the C# reference at MSDN. You can also find a link to the C# language specification at MSDN. I think the reason for the restriction probably derives from these statements in the language specification, section 4.1.5.

The char type is classified as an integral type, but it differs from the other integral types in two ways:

• There are no implicit conversions from other types to the char type. In particular, even though the sbyte, byte, and ushort types have ranges of values that are fully representable using the char type, implicit conversions from sbyte, byte, or ushort to char do not exist.

• Constants of the char type must be written as character-literals or as integer-literals in combination with a cast to type char. For example, (char)10 is the same as '\x000A'.


This is workaround I'm using

enum MyEnum
{
    AA = 'A',
    BB = 'B',
    CC = 'C'
};

static void Main(string[] args)
{
    MyEnum e = MyEnum.AA;
    char value = (char)e.GetHashCode(); //value = 'A'
}

Tags:

C#

Enums

Char