In fact the enum
is using the type int
and I can prove:
using static System.Console;
public class Program {
public static void Main() {
WriteLine(PayCode.NotPaid.GetTypeCode());
WriteLine((int)(PayCode.NotPaid));
WriteLine((char)(PayCode.NotPaid));
Teste('A');
int x = 'B';
}
public static void Teste(int x) {}
}
public enum PayCode {
NotPaid = 'N',
Paid = 'P'
}
Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.
So what happened? A promotion like char
for a int
. All char
can be automatically considered as a numerical type larger than it, as the int
if the site expects it. So, in addition to showing what is the internal type of the enum
, used showing in other contexts where one expects int
that send a char
it’s okay.
This rule was defined by language. Is it correct? In other languages it was always easy to answer this because the type char
actually it was just a number that by chance could be interpreted as if it were an ASCII table character. In C# it could be different since it has better abstractions, and has kind that was numerical and did not accept to convert automatically (bool
), but they thought it best to keep the same semantics in this case.
And note that you can show the real value of the enumeration, if you really need to do this, saying how you want to show and works for both integer and character. But make no mistake, in memory you will have a saved integer where you have a value of that enumeration, as shown in the first line of the code.
In c# char is a 16-bit integer (2 bytes), each character is encoded in a numeric code (look for UNICODE encoding), so they are compatible types for conversion. There are numerous encodings, but the default for strings in c# is UNICODE. Curiosity: Emojis occupy 2 characters (look for surrogate).
– user178974