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 defau
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!
Character enums would simply be strings wouldn't they? I'm not sure what other benefit you would derive from a character enumeration?
As others have said, the default type is int for an enumeration.
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());
}
}
See ECMA standard 335, Common Language Infrastructure (CLI), in Ecma International. The CLI allows the underlying type to be char or bool but C# and VB.Net don't allow it. For what it is worth, C++/CLI does allow System::Char as the underlying type.
I presume that C# and VB.Net don't allow char and bool as the underlying type for syntactical reasons only.
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'
}
Technically, you can't do this. But, you can convert the enum to a byte and then convert that to char. This is useful if your goal is to have something like this (realizing this is impossible to do:
public enum CharEnum
{
one = '1'
}
You can do this, however, by using ASCII byte values and then converting:
public enum CharEnum
{
one = 49,
two = 50
}
You can then convert to byte and to char to get the char value. It is not really pretty, but it will work, if getting a char is your ultimate goal. You can also use unicode and an int value, if you need chars outside of the ASCII range. :-)