Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to prevent accidental bitwise operators on non-bitmask field?

In C# you are recommended to add the [Flags] attribute to bitmask enumerations, like so:

[Flags]
public enum Condiments
{
    None = 0,
    Ketchup = 1,
    Mustard = 2,
    Mayo = 4,
    Pickle = 8,
    AllTheWay = 15
}

I discovered I had code that erroneously performed bitwise operations on an enumeration without the [Flags] attribute that was not a bitmask at all (First=1, Second=2, Third=3, etc.). This was of course logically wrong, but perfectly acceptable to the compiler.

I'm wondering if there's any way to leverage the [Flags] attribute, or some other approach, to turn this into a compile-time error/warning. I don't know where to begin, but it seems like it should be doable, so any help would be appreciated.

like image 869
Joel P. Avatar asked Nov 14 '22 16:11

Joel P.


1 Answers

I would suggest for this "custom" checks, where compiler is not able to figure out the problem use http://research.microsoft.com/en-us/projects/contracts/. CodeContracts, if you can.

like image 131
Tigran Avatar answered Dec 17 '22 23:12

Tigran