Why we can't have “char” enum types

2019-01-18 08:30发布

I want to know why we can't have "char" as underlying enum type. As we have byte,sbyte,int,uint,long,ulong,short,ushort as underlying enum type. Second what is the default underlying type of an enum?

标签: c# enums char
8条回答
Ridiculous、
2楼-- · 2019-01-18 09:04

Pretty much everything has been said already about that. Just wanted to say you can use extensions if you use a lot of "char enums":

public enum MyEnum
{
    MY_VALUE = 'm'
}

public static class MyExtensions
{
    public static char GetChar(this Enum value)
    {
        return (char)value.GetHashCode();
    }
}

class Program
{
    public static void Main(string[] args)
    {
        MyEnum me = MyEnum.MY_VALUE;
        Console.WriteLine(me + " = " + me.GetChar());
    }
}
查看更多
来,给爷笑一个
3楼-- · 2019-01-18 09:07

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!

查看更多
登录 后发表回答