Search code examples
vb.netfor-loopreverseunsigned-integer

How do you specify a negative step for an unsigned integer index in a VB.net for-loop


How do you specify a negative step on a unsigned integer index for a for-loop in VB.net

The following code will not compile:

Option Strict

For i as uLong = uLong.maxvalue To 0 Step -1UL
  ...
next i

Gives this: Error: BC30439 Constant expression not representable in type 'ULong'


Solution

  • A unsigned Int16/Int32/Int64 cannot be represented as negative value, there is no way to do that, see ULong.MinValue.

    You have two options here:

      1. Simulatte a negative step by using a while/until loop:

        Dim i As ULong = ULong.MaxValue
        
        While (i <> ULong.MinValue)
            Console.WriteLine(i)
            i -= 1UL ' Decrement current value by desired amount.
        End While
        
      1. Set the /removeintchecks vb's compiler parameter, then you can use negative values for unsigned datatypes.

        Note that you can set this parameter in a guided way trough the configuration page of the solution, in the "Advanced Compile Options", check "Remove Integer Overflow Checks".