Search code examples
c#vb.netcode-conversion

Convert C# function to VB, char value overflow error


I need the following function converted to VB.NET, but I'm not sure how to handle the statement

res = (uint)((h * 0x21) + c);

Complete function:

private static uint convert(string input)
{
    uint res = 0;
    foreach (int c in input)
        res = (uint)((res * 0x21) + c);
    return res;
}

I created the following, but I get an overflow error:

Private Shared Function convert(ByVal input As String) As UInteger

    Dim res As UInteger = 0
    For Each c In input
        res = CUInt((res * &H21) + Asc(c)) ' also tried AscW 
    Next
    Return res

End Function

What am I missing? Can someone explain the details?


Solution

  • Your code is correct. The calculation is overflowing after just a few characters since res increases exponentially with each iteration (and it’s not the conversion on the character that’s causing the overflow, it’s the unsigned integer that overflows).

    C# by default allows integer operations to overflow – VB doesn’t. You can disable the overflow check in the project settings of VB, though. However I would try not to rely on this. Is there a reason this particular C# has to be ported? After all, you can effortlessly mix C# and VB libraries.