VB6 and .NET integer division

Description

In VBUC versions lower than 8.2, the division between two integers is migrated to a non-equivalent statement.

Consider the following VB6 code:

VB6 Code

Dim nLineCnt As Long
Dim nSplit As Long
Dim nItems As Long

'more code'

nItems = CLng(nLineCnt / nSplit)

The code was migrated to this:

.NET Code

int nLineCnt = 0;
int nSplit = 0;
int nItems = 0;

//more code 

nItems = nLineCnt / nSplit;

That division statement is not equivalent in .NET because, for operands of integer type, the / operator returns an integer, consisting of the quotient rounded towards zero.

Consider the following examples:

VB6 Code

Dim nLineCnt As Long
Dim nSplit As Long
Dim nItems As Long

'more code'

nLineCnt = 13
nSplit = 5

nItems = CLng(nLineCnt / nSplit) 'nItems is 3'

The result in VB6 is 3.

.NET Code

int nLineCnt = 13;
int nSplit = 5;
int nItems = 0;

//more code 

nItems = nLineCnt / nSplit; //nItems is 2

The result in .NET is 2.

To obtain a floating-point quotient, one of the operands should be cast as float, double, or decimal type:

.NET Code

int nLineCnt = 13;
int nSplit = 5;
int nItems = 0;

//more code 

nItems = Convert.ToInt32((double)nLineCnt / nSplit); //nItems is 3

The result with the modifications is 3.

The code is now equivalent. Notice the result should be converted to an integer.

Last updated