Reputation: 33
Got a problem with a code conversion from C# to VB.Net.
var x = 5783615;
var y = 56811584;
var t = x * y;
x, y and t are integers. In c# 't' will be -1553649728. In VB.Net, I will get an integer overflow exception.
Any idea how to fix it?
Upvotes: 3
Views: 3139
Reputation: 25066
You can get the same value as C# does ignoring overflow by calculating the product in 64 bits and then using only 32 bits of the result:
Dim x As Integer = 5783615
Dim y As Integer = 56811584
Dim tmp As Int64 = Convert.ToInt64(x) * Convert.ToInt64(y)
Dim bb = BitConverter.GetBytes(tmp)
Dim t = BitConverter.ToInt32(bb, 0)
' t is now -1553649728
Upvotes: 4
Reputation: 5552
You need explicit type definition to avoid this as the definition will be implicitly taken from the values. In vb.net try:
dim x as int = 5783615
dim y as int = 56811584
dim t as int = x * y
There may be other ways of doing this but this should be a start. In C# you might also try int or int32 or int64.
Good luck.
Upvotes: 0
Reputation: 564891
C#, by default, doesn't check for overflows, but VB does (by default).
You can setup your VB Project to not check for integer overflows in the Advanced Compile Options in the Compile tab. This will cause that specific project to stop raising OverflowException in cases like this.
Upvotes: 6