vb.netbitwise-andoverflowexception

Why bitwise AND operator of big ULong number with constant causes OverflowException?


This code compiles successfully, but causes System.OverflowException in Visual Studio 2013 during execution:

Sub Main()
    Dim a As ULong = 14345389830683080345D
    Dim c As ULong = 1

    Dim x As ULong = a And 1 '<-- cause System.OverflowException
    Dim y As ULong = a And c '<-- works well
End Sub

Can you explain me why is this happen? And if a variable has small value (e.g. 5), exception doesn't occur.

P.S. Three most significant bits of a variable are all zeros.


Solution

  • The result of using bitwise 'And' on a ULong and an Integer is 'Long' - this is your first case. The overflow is not happening on assignment, but in the evaluation of the 'And' expression itself - it doesn't fit into a 'Long'. The result on a ULong and ULong is 'ULong' - this is your second case.

    The types of these values matters. The literal '1' defaults to 'Integer'.

    Btw, an easy way to find the result for these is to set Option Infer On and type some examples in VB, such as "Dim v = 1 And 2", then view the compiler's typing of 'v' by hovering over it.