Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use unsafe values in an enum?

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
}
like image 430
Jon Tackabury Avatar asked Apr 12 '10 15:04

Jon Tackabury


People also ask

Can enum take null values?

Enum types cannot be nullable.

Can we change enum values?

Enum constants are implicitly static and final and you can not change their value once created. Enum in Java provides type-safety and can be used inside switch statements like int variables.

Can enums be overridden?

By default, the enum value is its method name. You can however override it, for example if you want to store enums as integers in a database, instead of using their method name. An enum value doesn't have to be a string, as you can see in the example.

Can you add values to enum?

You can add a new value to a column of data type enum using ALTER MODIFY command. If you want the existing value of enum, then you need to manually write the existing enum value at the time of adding a new value to column of data type enum.


1 Answers

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

like image 122
AakashM Avatar answered Sep 23 '22 15:09

AakashM