views:

112

answers:

4

I need to use this enum in my C# application, but it won't let me use these values. When I specify the type as uint I can use the -1 value, and when I specify int I can't use the last 2 values. Is there a way to use the unchecked keyword here to allow me to define all of these values? These values are coming from an external source, so I can't change them.

internal enum MyValues : int
{
    value1 = -1,
    value2 = 0,
    value3 = 0x80000000,
    value4 = 0xFFFFFFFF
}
A: 

Maybe try ulong enums instead of int?

devoured elysium
+7  A: 

If you want -1 to be a different value from 0xFFFFFFFF, you're going to need a datatype bigger than 32 bits. Try long.

AakashM
Using a 64bit data type isn't an option, I'm using interop to return a 32bit value.
Jon Tackabury
If -1 and 0xFFFFFFFF are technically the same thing when using a uint, I guess I can just remove the -1 value?
Jon Tackabury
@Jon: -1 doesn't exist when you're using uint - you'd have to make an unchecked conversion.
Jon Skeet
I know that -1 doesn't exist, I want it to overflow and wrap around. I guess if it did that, -1 would just be 0xFFFFFFFF, correct?
Jon Tackabury
@Jon T : Exactly. The two's complement representation of -1 has all bits set - so in 32 bits, this is the same as `0xFFFFFFFF` as an unsigned.
AakashM
+1  A: 

It's typically not a good idea to use unsafe anywhere in a C# application. Since these values look to be constant, just create a static class to just hold the values. You'll have another file, but you will have your problem solved. And you can use whatever 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;
}
Mike Webb
+2  A: 

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

Jon Seigel
Wrote this big long post and then noticed you said the same thing. +1. @Jon Tackabury: @Jon Seigel's answer is the most maintainable option. Do not assume -1 is the same as 0xFFFFFFFF unless you have very intimate knowledge of the library you're using.
Randolpho