Why integer arithmetic result showing different values in VB.NET and C#?

Viewed 128

I have converted C# decrypt/encrypt functions to VB.NET. When I test the result in C# is showing below result but in VB.NET it throws an exception. Could you explain to me how C# showing the below result?

Below codes are tested in VS 2010 with 4.0 framework.

C# Code

class Program
    {
        static void Main(string[] args)
        {
            byte bytTen = 10;
            int aa = 1527870874;
            int bb = 28904;
            int cc = 35756;
            Console.WriteLine((bytTen + aa) * bb + cc);
            Console.ReadKey();
        }
    }

Result: 726329420

VB.NET Code

Module Module1

    Sub Main()
        Dim bytTen As Byte = 10
        Dim aa As Integer = 1527870874, bb As Integer = 28904, cc As Integer = 35756
        Console.WriteLine((bytTen + aa) * bb + cc)
        Console.ReadKey()
    End Sub

End Module

Result: Arithmetic operation resulted in an overflow.

2 Answers

The C# code is running as unchecked code (where integer overflow is ignored).

The VB code is running in as checked, where the runtime detects an integer overflow and throws an exception.

To get the same result in VB, you need to check the project-level option "Remove integer overflow checks" on the "Advanced Compiler Settings" options via the "Compile" tab of the project options.

C# by default removes integer overflow checks (but this can also be changed on the C# project options), while VB by default has integer overflow checks.

Related