VB.NET vs C# integer division

C#.Netvb.netOperatorsDivision

C# Problem Overview


Anyone care to explain why these two pieces of code exhibit different results?

VB.NET v4.0

Dim p As Integer = 16
Dim i As Integer = 10
Dim y As Integer = p / i
//Result: 2

C# v4.0

int p = 16;
int i = 10;
int y = p / i;
//Result: 1

C# Solutions


Solution 1 - C#

When you look at the IL-code that those two snippets produce, you'll realize that VB.NET first converts the integer values to doubles, applies the division and then rounds the result before it's converted back to int32 and stored in y.

C# does none of that.

VB.NET IL Code:

IL_0000:  ldc.i4.s    10 
IL_0002:  stloc.1     
IL_0003:  ldc.i4.s    0A 
IL_0005:  stloc.0     
IL_0006:  ldloc.1     
IL_0007:  conv.r8     
IL_0008:  ldloc.0     
IL_0009:  conv.r8     
IL_000A:  div         
IL_000B:  call        System.Math.Round
IL_0010:  conv.ovf.i4 
IL_0011:  stloc.2     
IL_0012:  ldloc.2     
IL_0013:  call        System.Console.WriteLine

C# IL Code:

IL_0000:  ldc.i4.s    10 
IL_0002:  stloc.0     
IL_0003:  ldc.i4.s    0A 
IL_0005:  stloc.1     
IL_0006:  ldloc.0     
IL_0007:  ldloc.1     
IL_0008:  div         
IL_0009:  stloc.2     
IL_000A:  ldloc.2     
IL_000B:  call        System.Console.WriteLine

The "proper" integer division in VB needs a backwards slash: p \ i

Solution 2 - C#

In VB, to do integer division, reverse the slash:

Dim y As Integer = p \ i

otherwise it is expanded to floating-point for the division, then forced back to an int after rounding when assigned to y.

Solution 3 - C#

VB.NET integer division operator is \, not /.

Solution 4 - C#

"Division is performed differently in C# and VB. C#, like other C-based languages truncates the division result when both operands are integer literals or integer variables (or integer constants). In VB, you must use the integer division operator (\) to get a similar result."

Source

Solution 5 - C#

In C#, integer division is applied with / when both numerator and denomenator are integers. Whereas, in VB.Net '/' results in floating point divsion, so for integer division in VB.Net use \. Have a look at this MSDN post.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMaxim GershkovichView Question on Stackoverflow
Solution 1 - C#ChristianView Answer on Stackoverflow
Solution 2 - C#Marc GravellView Answer on Stackoverflow
Solution 3 - C#OdedView Answer on Stackoverflow
Solution 4 - C#lanceView Answer on Stackoverflow
Solution 5 - C#FIre PandaView Answer on Stackoverflow