简体   繁体   中英

Logic Error while converting VB.Net Code to C#

I have this VB.Net Code:

Dim t as String = "111100111000011110111110010111101001100001100011101000001010011100110110100110100000101001110010011001101"
Dim i as Integer
If (t.Length Mod 8) <> 0 Then
    For i = 1 To 8 - (t.Length Mod 8)
        t = "0" + t
    Next
End If

When I convert it to C# it becomes:

string t = "111100111000011110111110010111101001100001100011101000001010011100110110100110100000101001110010011001101";

int i = 0;
if ((t.Length % 8) != 0)
{
    for (i = 1; i <= (8 - (t.Length%8)); i++)
    {
        t = "0" + t;
    }
}

The problem is the two codes are not same result. so the VB.net code is executing 7 times and the C# code is executing 4 times.

Please tell me what is the problem!

For boundaries in VB are pre-calculated and do not change while the loop is executed. So t.Length Mod 8 is calculated once and then this value is used.

In C# the condition is evaluated each time, and because you keep changing t , t.Length Mod 8 gives new value each time.

Also because strings are immutable in .NET, your code generates up to 7 copies of t . You should really do this:

Dim diff As Integer = t.Length Mod 8

If diff <> 0 Then
    t = New String("0"c, 8 - diff) & t
End If

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