Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile Time Conversion of uint to int in C#

Tags:

c#

clr

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?

like image 985
Billy ONeal Avatar asked Aug 08 '12 21:08

Billy ONeal


1 Answers

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);
} 
like image 86
Monroe Thomas Avatar answered Oct 17 '22 22:10

Monroe Thomas