开发者

.NET Enum base type of Char

According to msdn Enums cannot have a base type of char. Why can enums not have a base type of char? Also why does microsoft strongly recommend that an enum contain a constant with a value of 0开发者_运维技巧? Thank you very much


You can find a link to the C# language specification. 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'.

As far as why zero, because the default value of an uninitialized enum is 0.


Although as you've seen here, you are specifically not allowed to define a character enum because there is no implicit conversion from char to any other integral type, there is an integral conversion from char to integer, so you can do this:

public enum MyCharEnum
{
    BEL = 0x07,
    CR = 0x0D,
    A = 'A',
    z = 'z'
}

And use an explicit conversion to char, thus:

MyCharEnum thing = MyCharEnum.BEL;
char ch = (char)thing;
System.Console.WriteLine(ch.ToString());

(and, yes, it makes a beep - just like the good old days!)


Why can enums not have a base type of char?

Because it doesn't really make sense (in much the same way that having a base type of float doesn't make sense). Under the covers an enum is an integer, however as a char can be any unicode character there isn't really a stuiable mapping from chars to integers.

Why does microsoft strongly recommend that an enum contain a constant with a value of 0?

Because the default value of an un-initialised enum is zero (see Enums should have zero value)


Why can enums not have a base type of char?

I would suggest that this is due to the way that .NET handles Chars as unicode meaning that a Char != Byte (it's value can be greater than 255). Enum's cannot be based on a Boolean type either and that is also an integral type. Also using a Char as the base type wouyld duplicate an existing base type so there is no point in doing so.

Why does microsoft strongly recommend that an enum contain a constant with a value of 0?

The reason why you are recommended to always have a value equal to 0 is because an enum is a value type and when a new one is made it will have the value of 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜