1

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!

GSerg
  • 76,472
  • 17
  • 159
  • 346
Alaa Masalmeh
  • 57
  • 1
  • 9
  • 2
    as @GSerg said in his answer about precalulation but this code you want to add 0 to the beginning of the whole string if it's not alt least 8 if i understand. you should use `t = t.PadLeft(t.Length + (t.Length % 8),'0');` and that's it – Franck Apr 07 '15 at 11:39

1 Answers1

10

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
GSerg
  • 76,472
  • 17
  • 159
  • 346