How to use unsafe values ​​in an enumeration?

I need to use this enumeration in my C # application, but this will not allow me to use these values. When I specify the type as uint, I can use the value -1, and when I specify int, I cannot use the last 2 values. Is there a way to use the unchecked keyword so that I can define all of these values? These values ​​come from an external source, so I cannot change them.

internal enum MyValues : int { value1 = -1, value2 = 0, value3 = 0x80000000, value4 = 0xFFFFFFFF } 
+7
enums c # interop unsafe
source share
5 answers

If you want -1 different from 0xFFFFFFFF , you will need a data type larger than 32 bits. Try long .

+9
source share

0xFFFFFFFF is a 32-bit number, so it should match enum: int (I feel the long type is the excess :))

You tried

 enum YourEnum : int { /*...*/, value4 = unchecked( (int)0xFFFFFFFF ) }; 
+3
source share

Since these values ​​look constant, just create a static class to hold the values. In addition, you can use any types you want:

 public static class MyValues { public const int value1 = -1; public const int value2= 0; public const int value3 = 0x80000000; public const int value4 = 0xFFFFFFFF; } 
+2
source share

One way to solve this problem is to use normal values ​​for enum (0, 1, 2, 3) and create a class or pair of methods to convert input values ​​to enum members and vice versa -versa.

+2
source share

Maybe try ulong enums instead of int?

+1
source share

All Articles