简体   繁体   中英

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM