I'm having a problem to translate following code from C# to VB.NET.
C# code
public static byte Crc8(byte[] data, int size) {
byte checksum = 0;
for (int i=0; i<=size; i++)
checksum += data[i];
return (byte)(-checksum);
}
VB.NET code
Public Shared Function Crc8(ByVal data As Byte(), ByVal size As Integer) As Byte
Dim checksum As Byte = 0
For i As Integer = 0 To size - 1
checksum += data(i)
Next
Return CByte(-checksum)
End Function
Problem is that the VB code results in a "Arithmetic operation resulted in an overflow." error.
It seems that the "+=" operator does not operate the same way. In VB it's actually creating a sum (100 + 200 = 300) and in C# it's performing some kind of operation on the bytes (100 + 200 = 44). I can't seem to find what operation it's doing.
For future reference, the solution was:
The difference is that by default, C# handles overflow by just wrapping - so 255 + 1 will end up as 0. In VB - by default, again - the overflow throws
System.OverflowException
.In C#, you can control this in a fine-grained way using the
checked
andunchecked
keywords. You can also change the default for a whole project. So for example, in Noda Time I've turned on checked arithmetic in order to spot overflows, but I deliberate turn it off for hash code generation (where overflow is likely and harmless) by using anunchecked
block.Unfortunately as far as I can tell, VB doesn't have the fine-grained control. You can turn overflow checking off for a whole project using the "Remove Integer Overflow Checks" option, but you can't do it for just some sections of the code.
So in your case, you either need to move this bit of code to a different project where you can turn overflow checking off, or you need to live with overflow checking being off for your whole project.
(As an aside, it looks like this makes implementing
GetHashCode
in VB a bit of a pain.)