Unexpected behavior between [Flags] enumeration: long vs [Flags] enum: ulong

Compiles but should not

[Flags]
enum TransactionData : long  // 64 bits.  Last bit is sign bit, but I'm putting data there
{
    None = 0,
    Color1 = 1 << 63,
}

Mistakes but should not

[Flags]
enum TransactionData : ulong  // 64 bits. No sign bit.  Not allowed to put data there
{
    None = 0,
    Color1 = 1 << 63,
}

Compiler error text:

-2147483648 could not be converted to ulong

Question:

I would expect the opposite to happen. Can anyone explain why this is so?

Also, how can I print this flag with attribute byte[]to check?

 var eee  = TransactionData.None | TransactionData.Color1
 // How do I convert eee to byte[]?
+4
source share
1 answer

Please note that is 1 << 63not ulongor even long. The compiler interprets it as int. Take a look at the following example:

enum TransactionData : long
{
    None = 0,
    Color1 = 1 << 31,
    Color2 = 1 << 63,
}

Console.WriteLine(TransactionData.Color1 == TransactionData.Color2); // True

ulong, ul :

enum TransactionData : ulong
{
    None = 0,
    Color1 = 1ul << 63,
}

L, L 1. , , .

, , 1ul << 63 64 ( , 63 ).

+11

Source: https://habr.com/ru/post/1531450/


All Articles