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?
First of all, YES, we can assign an Enum to something else, a char !
An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it.
We can't define enumeration as string type. The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or ulong.
The enum can be of any numeric data type such as byte, sbyte, short, ushort, int, uint, long, or ulong. However, an enum cannot be a string type.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With