How to: Optimize Storage of Positive Integers With Unsigned Types (Visual Basic)

If you have a variable that contains only positive values (or 0), and these values never exceed 4,294,967,295, you can declare the variable as UInteger instead of Long.

The advantage of using UInteger is that the 32-bit integer types Integer and UInteger are the most efficient data types on 32-bit platforms, and they provide optimum performance for your application.

You can use an Integer variable if your positive values never exceed 2,147,483,647.

To declare an integer with only positive values

  • Declare the variable As UInteger. The following example illustrates this.

    Public Function memoryRequired(ByVal m As UInteger) As UInteger
        Static r As UInteger = 0
        Try
            r += m
        Catch eo As System.OverflowException
            r = 0
        Catch ex As System.Exception
            MsgBox("Incrementing required memory causes """ & ex.Message & """")
        End Try
        Return r
    End Function
    

    You can test the function memoryRequired with the following code:

    Public Sub consumeMemoryRequired()
        Dim m1 As UInteger = UInteger.MaxValue - 100
        Dim m2 As UInteger = 100
        MsgBox("Max = " & CStr(UInteger.MaxValue) & vbCrLf & 
            CStr(m1) & " -> " & CStr(memoryRequired(m1)) & vbCrLf & 
            "+ " & CStr(m2) & " -> " & CStr(memoryRequired(m2)) 
            & vbCrLf & "+ 1 -> " & CStr(memoryRequired(1)))
    End Sub
    

    Warning

    The UInteger data type is not part of the Common Language Specification (CLS), so CLS-compliant code cannot consume a component that uses it.

See Also

Tasks

How to: Call a Windows Function that Takes Unsigned Types (Visual Basic)

Reference

Data Type Summary (Visual Basic)

Integer Data Type (Visual Basic)

UInteger Data Type