I've got an enum like this in an old piece of code:
[Flags]
public enum Example: uint
{
Foo = 0x00000001,
Bar = 0xC0000000
}
Now, FxCop is complaining about this enum using uint rather than int as it's backing field. (And I've been tasked with getting this code as FxCop clean as possible...) But there is an existing enum value which uses the high order bit of the enum, and I can't change this because it has been persisted into an on-disk format. When I try to compile this, the C# compiler rightly complains:
error CS0266: Cannot implicitly convert type 'uint' to 'int'. An explicit conversion exists (are you missing a cast?)
So, I was going to change it to this instead:
[Flags]
public enum Example
{
Foo = 0x00000001,
Bar = (int)0xC0000000
}
However, I'm not positive that I can rely on this not throwing arithmetic exceptions, or not being handled correctly when being read or written to disk. Can I rely on the bit format here matching the format it used when the enum was backed by an unsigned int?
Use the unchecked keyword here and you will be ok; the persisted bit pattern will be what you expect.
[Flags]
public enum Example
{
Foo = 0x00000001,
Bar = unchecked((int)0xC0000000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With