In most languages, the concept AND has two different representations. For example, in F# there is logical AND:
let awesome = good && great
Then there is bitwise AND:
// this is pretty common when working with Flags let hasRed = someColors &&& Color.Red = Color.Red
But then there's VB, for which both concepts use the keyword
And. So I implemented a feature in VB to clone an image. I had this code snippet.
Public Shared Function CloneImage(ByVal sourceImage As Bitmap) As Bitmap If sourceImage.PixelFormat And PixelFormat.Indexed <> 0 Then Return CreateIndexedImage(sourceImage) Else Return CreateNonIndexedImage(sourceImage) End If End Function
This code always calls
CreateIndexedImage. And it took me a bit to figure out why. It was because the language sees the keyword
And as the lowest priority operator and evaluates it last. It does that because it is only considering the priority of logical
And. So the actual evaluation was something like
(sourceImage.PixelFormat) And (PixelFormat.Indexed <> 0). VB coerces the type of PixelFormat to be truthy, and the second condition will always be true.
The fix was to add parenthesis
If (sourceImage.PixelFormat And PixelFormat.Indexed) <> 0 Then
But this could have been avoided by simply having a different operator between the two uses. Then each could have a different order of precedence.