Why does a 'for' loop behave differently when migrating VB.NET code to C#?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP











up vote
61
down vote

favorite
7












I'm in the process of migrating a project from Visual Basic to C# and I've had to change how a for loop being used is declared.



In VB.NET the for loop is declared below:



Dim stringValue As String = "42"

For i As Integer = 1 To 10 - stringValue.Length
stringValue = stringValue & " " & CStr(i)
Console.WriteLine(stringValue)
Next


Which outputs:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


In C# the for loop is declared below:



string stringValue = "42";

for (int i = 1; i <= 10 - stringValue.Length; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3


This obviously isn't correct so I had to change the code ever so slightly and included an integer variable that would hold the length of the string.



Please see the code below:



string stringValue = "42";
int stringValueLength = stringValue.Length;

for (int i = 1; i <= 10 - stringValueLength; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


Now my question resolves around how Visual Basic differs to C# in terms of Visual Basic using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes. Whereas in C# if I use the stringValue.Length in the for loop condition it changes the initial string value each time the loop occurs. Why is this?










share|improve this question



















  • 5




    Microsoft clearly outlines what your problem is...
    – Çöđěxěŕ
    2 days ago






  • 37




    @Çöđěxěŕ: Stop, please. If robotically removing tags from the title without regard to context were helpful, the website would do it.
    – Ry-♦
    2 days ago







  • 9




    @Çöđěxěŕ You can find some info about that here
    – pushkin
    2 days ago






  • 32




    @Çöđěxěŕ I don't think that the two posts contradict each other. The point is: don't awkwardly stick a tag in the title like "question about this thing - tag". But if the title is a complete sentence that includes the tag, then it is sometimes ok. "Why does for loop behave differently when migrating" feels like a way too generic title.
    – pushkin
    2 days ago






  • 23




    @Çöđěxěŕ "migrating VB.NET code to C#" is clearly a full phrase that adds useful information to the title. Don't make edits that decrease clarity. Hopefully, that notion is common sense enough that we don't need a Meta post to back it up.
    – jpmc26
    2 days ago















up vote
61
down vote

favorite
7












I'm in the process of migrating a project from Visual Basic to C# and I've had to change how a for loop being used is declared.



In VB.NET the for loop is declared below:



Dim stringValue As String = "42"

For i As Integer = 1 To 10 - stringValue.Length
stringValue = stringValue & " " & CStr(i)
Console.WriteLine(stringValue)
Next


Which outputs:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


In C# the for loop is declared below:



string stringValue = "42";

for (int i = 1; i <= 10 - stringValue.Length; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3


This obviously isn't correct so I had to change the code ever so slightly and included an integer variable that would hold the length of the string.



Please see the code below:



string stringValue = "42";
int stringValueLength = stringValue.Length;

for (int i = 1; i <= 10 - stringValueLength; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


Now my question resolves around how Visual Basic differs to C# in terms of Visual Basic using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes. Whereas in C# if I use the stringValue.Length in the for loop condition it changes the initial string value each time the loop occurs. Why is this?










share|improve this question



















  • 5




    Microsoft clearly outlines what your problem is...
    – Çöđěxěŕ
    2 days ago






  • 37




    @Çöđěxěŕ: Stop, please. If robotically removing tags from the title without regard to context were helpful, the website would do it.
    – Ry-♦
    2 days ago







  • 9




    @Çöđěxěŕ You can find some info about that here
    – pushkin
    2 days ago






  • 32




    @Çöđěxěŕ I don't think that the two posts contradict each other. The point is: don't awkwardly stick a tag in the title like "question about this thing - tag". But if the title is a complete sentence that includes the tag, then it is sometimes ok. "Why does for loop behave differently when migrating" feels like a way too generic title.
    – pushkin
    2 days ago






  • 23




    @Çöđěxěŕ "migrating VB.NET code to C#" is clearly a full phrase that adds useful information to the title. Don't make edits that decrease clarity. Hopefully, that notion is common sense enough that we don't need a Meta post to back it up.
    – jpmc26
    2 days ago













up vote
61
down vote

favorite
7









up vote
61
down vote

favorite
7






7





I'm in the process of migrating a project from Visual Basic to C# and I've had to change how a for loop being used is declared.



In VB.NET the for loop is declared below:



Dim stringValue As String = "42"

For i As Integer = 1 To 10 - stringValue.Length
stringValue = stringValue & " " & CStr(i)
Console.WriteLine(stringValue)
Next


Which outputs:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


In C# the for loop is declared below:



string stringValue = "42";

for (int i = 1; i <= 10 - stringValue.Length; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3


This obviously isn't correct so I had to change the code ever so slightly and included an integer variable that would hold the length of the string.



Please see the code below:



string stringValue = "42";
int stringValueLength = stringValue.Length;

for (int i = 1; i <= 10 - stringValueLength; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


Now my question resolves around how Visual Basic differs to C# in terms of Visual Basic using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes. Whereas in C# if I use the stringValue.Length in the for loop condition it changes the initial string value each time the loop occurs. Why is this?










share|improve this question















I'm in the process of migrating a project from Visual Basic to C# and I've had to change how a for loop being used is declared.



In VB.NET the for loop is declared below:



Dim stringValue As String = "42"

For i As Integer = 1 To 10 - stringValue.Length
stringValue = stringValue & " " & CStr(i)
Console.WriteLine(stringValue)
Next


Which outputs:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


In C# the for loop is declared below:



string stringValue = "42";

for (int i = 1; i <= 10 - stringValue.Length; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3


This obviously isn't correct so I had to change the code ever so slightly and included an integer variable that would hold the length of the string.



Please see the code below:



string stringValue = "42";
int stringValueLength = stringValue.Length;

for (int i = 1; i <= 10 - stringValueLength; i ++)

stringValue = stringValue + " " + i.ToString();
Console.WriteLine(stringValue);



And the output:



42 1
42 1 2
42 1 2 3
42 1 2 3 4
42 1 2 3 4 5
42 1 2 3 4 5 6
42 1 2 3 4 5 6 7
42 1 2 3 4 5 6 7 8


Now my question resolves around how Visual Basic differs to C# in terms of Visual Basic using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes. Whereas in C# if I use the stringValue.Length in the for loop condition it changes the initial string value each time the loop occurs. Why is this?







c# vb.net loops for-loop






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 22 mins ago









Peter Mortensen

13.1k1983111




13.1k1983111










asked 2 days ago









slee423

5671422




5671422







  • 5




    Microsoft clearly outlines what your problem is...
    – Çöđěxěŕ
    2 days ago






  • 37




    @Çöđěxěŕ: Stop, please. If robotically removing tags from the title without regard to context were helpful, the website would do it.
    – Ry-♦
    2 days ago







  • 9




    @Çöđěxěŕ You can find some info about that here
    – pushkin
    2 days ago






  • 32




    @Çöđěxěŕ I don't think that the two posts contradict each other. The point is: don't awkwardly stick a tag in the title like "question about this thing - tag". But if the title is a complete sentence that includes the tag, then it is sometimes ok. "Why does for loop behave differently when migrating" feels like a way too generic title.
    – pushkin
    2 days ago






  • 23




    @Çöđěxěŕ "migrating VB.NET code to C#" is clearly a full phrase that adds useful information to the title. Don't make edits that decrease clarity. Hopefully, that notion is common sense enough that we don't need a Meta post to back it up.
    – jpmc26
    2 days ago













  • 5




    Microsoft clearly outlines what your problem is...
    – Çöđěxěŕ
    2 days ago






  • 37




    @Çöđěxěŕ: Stop, please. If robotically removing tags from the title without regard to context were helpful, the website would do it.
    – Ry-♦
    2 days ago







  • 9




    @Çöđěxěŕ You can find some info about that here
    – pushkin
    2 days ago






  • 32




    @Çöđěxěŕ I don't think that the two posts contradict each other. The point is: don't awkwardly stick a tag in the title like "question about this thing - tag". But if the title is a complete sentence that includes the tag, then it is sometimes ok. "Why does for loop behave differently when migrating" feels like a way too generic title.
    – pushkin
    2 days ago






  • 23




    @Çöđěxěŕ "migrating VB.NET code to C#" is clearly a full phrase that adds useful information to the title. Don't make edits that decrease clarity. Hopefully, that notion is common sense enough that we don't need a Meta post to back it up.
    – jpmc26
    2 days ago








5




5




Microsoft clearly outlines what your problem is...
– Çöđěxěŕ
2 days ago




Microsoft clearly outlines what your problem is...
– Çöđěxěŕ
2 days ago




37




37




@Çöđěxěŕ: Stop, please. If robotically removing tags from the title without regard to context were helpful, the website would do it.
– Ry-♦
2 days ago





@Çöđěxěŕ: Stop, please. If robotically removing tags from the title without regard to context were helpful, the website would do it.
– Ry-♦
2 days ago





9




9




@Çöđěxěŕ You can find some info about that here
– pushkin
2 days ago




@Çöđěxěŕ You can find some info about that here
– pushkin
2 days ago




32




32




@Çöđěxěŕ I don't think that the two posts contradict each other. The point is: don't awkwardly stick a tag in the title like "question about this thing - tag". But if the title is a complete sentence that includes the tag, then it is sometimes ok. "Why does for loop behave differently when migrating" feels like a way too generic title.
– pushkin
2 days ago




@Çöđěxěŕ I don't think that the two posts contradict each other. The point is: don't awkwardly stick a tag in the title like "question about this thing - tag". But if the title is a complete sentence that includes the tag, then it is sometimes ok. "Why does for loop behave differently when migrating" feels like a way too generic title.
– pushkin
2 days ago




23




23




@Çöđěxěŕ "migrating VB.NET code to C#" is clearly a full phrase that adds useful information to the title. Don't make edits that decrease clarity. Hopefully, that notion is common sense enough that we don't need a Meta post to back it up.
– jpmc26
2 days ago





@Çöđěxěŕ "migrating VB.NET code to C#" is clearly a full phrase that adds useful information to the title. Don't make edits that decrease clarity. Hopefully, that notion is common sense enough that we don't need a Meta post to back it up.
– jpmc26
2 days ago













5 Answers
5






active

oldest

votes

















up vote
91
down vote



accepted










In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop.



So, in the C# version in the question, because the length of stringValue is being changed in the loop, the final loop variable value will be changed.



In VB.NET, the final condition is inclusive, so you would use <= instead of < in C#.






share|improve this answer






















  • Thanks for the reply. I now realise that using <= allows me to iterate and have the same output as the VB code. However, I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to. I'm going to update my question to show the same output.
    – slee423
    2 days ago










  • @slee423 The reason is given in the first sentence of my answer. Because the length of stringValue is being changed in the loop, the final loop variable value will be changed.
    – Andrew Morton
    2 days ago






  • 1




    apologies, thanks for that answer. And thanks for elaborating it in more detail for me.
    – slee423
    2 days ago






  • 1




    @slee423 I added that into the answer as it does indeed clarify it.
    – Andrew Morton
    2 days ago

















up vote
19
down vote














Now my question resolves around how VB differs to C# in terms of VB using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes.




According to the VB.NET documentation:




If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.




So, the value of To 10 - stringValue.Length is evaluated once and reused until the loops exit.



However, look at c#'s for statement




If the for_condition is not present or if the evaluation yields true, control is transferred to the embedded statement. When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), the expressions of the for_iterator, if any, are evaluated in sequence, and then another iteration is performed, starting with evaluation of the for_condition in the step above.




Which basically means that the condition ; i <= 10 - stringValueLength; is evaluated again each time.



So, as you saw, if you want to replicate the code, you need to declare the final counter in c# before starting the loop.






share|improve this answer
















  • 4




    The end condition evaluation has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
    – Andrew Morton
    2 days ago

















up vote
9
down vote













In order to make the example more understandable, I will convert both for loops into C# while loops.



VB.NET



string stringValue = "42";

int min = 1;
int max = 10 - stringValue.Length;
int i = min;
while (i <= max)

stringValue = stringValue + " " + stringValue.Length.ToString();
Console.WriteLine(stringValue);
i++;



C#



string stringValue = "42";

int i = 1;
while (i <= 10 - stringValue.Length)

stringValue = stringValue + " " + stringValue.Length.ToString();
Console.WriteLine(stringValue);
i++;



The difference is then:




VB.NET caches the maximum value for i, but C# recomputes it every time.







share|improve this answer


















  • 2




    You don't need to convert loops to while
    – Panagiotis Kanavos
    2 days ago






  • 10




    It helped me to understand the for loops at my begins, I think they are much more understandable. This is why I 'translated' the examples in while loops, to help understanding.
    – Maxime Recuerda
    2 days ago

















up vote
5
down vote













Because the for in VB is a different semantic than the for in C# (or any other C-like language)



In VB, the for statement is specifically incrementing a counter from one value to another.



In C, C++, C#, etc., the for statement simply evaluates three expressions:



  • The first expression is customarily an initialization

  • The second expression is evaluated at the start of each iteration to determine whether the terminal condition has been met

  • The third expression is evaluated at the end of each iteration, which is customarily an incrementer.

In VB, you must supply a numeric variable which can be tested against a terminal value and incremented on each iteration



In C, C++, C#, etc., the three expressions are minimally constrained; the conditional expression must evaluate to a true/false (or integer zero/non-zero in C, C++). You don't need to perform an initialization at all, you can iterate any type over any range of values, iterate a pointer or reference over a complex structure, or not iterate anything at all.



So, in C#, etc., the condition expression must be fully evaluated on each iteration, but in VB, the terminal value of the iterator must be evaluated at the beginning, and need not be evaluated again.






share|improve this answer





























    up vote
    -3
    down vote














    I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to.




    In VB, type the declaration is optional depending on the existence of the Option Explicit setting in the file.






    share|improve this answer






















    • The integer variable they’re referring to is stringValueLength.
      – Ry-♦
      yesterday










    Your Answer





    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: false,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52607611%2fwhy-does-a-for-loop-behave-differently-when-migrating-vb-net-code-to-c%23new-answer', 'question_page');

    );

    Post as a guest






























    5 Answers
    5






    active

    oldest

    votes








    5 Answers
    5






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    91
    down vote



    accepted










    In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop.



    So, in the C# version in the question, because the length of stringValue is being changed in the loop, the final loop variable value will be changed.



    In VB.NET, the final condition is inclusive, so you would use <= instead of < in C#.






    share|improve this answer






















    • Thanks for the reply. I now realise that using <= allows me to iterate and have the same output as the VB code. However, I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to. I'm going to update my question to show the same output.
      – slee423
      2 days ago










    • @slee423 The reason is given in the first sentence of my answer. Because the length of stringValue is being changed in the loop, the final loop variable value will be changed.
      – Andrew Morton
      2 days ago






    • 1




      apologies, thanks for that answer. And thanks for elaborating it in more detail for me.
      – slee423
      2 days ago






    • 1




      @slee423 I added that into the answer as it does indeed clarify it.
      – Andrew Morton
      2 days ago














    up vote
    91
    down vote



    accepted










    In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop.



    So, in the C# version in the question, because the length of stringValue is being changed in the loop, the final loop variable value will be changed.



    In VB.NET, the final condition is inclusive, so you would use <= instead of < in C#.






    share|improve this answer






















    • Thanks for the reply. I now realise that using <= allows me to iterate and have the same output as the VB code. However, I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to. I'm going to update my question to show the same output.
      – slee423
      2 days ago










    • @slee423 The reason is given in the first sentence of my answer. Because the length of stringValue is being changed in the loop, the final loop variable value will be changed.
      – Andrew Morton
      2 days ago






    • 1




      apologies, thanks for that answer. And thanks for elaborating it in more detail for me.
      – slee423
      2 days ago






    • 1




      @slee423 I added that into the answer as it does indeed clarify it.
      – Andrew Morton
      2 days ago












    up vote
    91
    down vote



    accepted







    up vote
    91
    down vote



    accepted






    In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop.



    So, in the C# version in the question, because the length of stringValue is being changed in the loop, the final loop variable value will be changed.



    In VB.NET, the final condition is inclusive, so you would use <= instead of < in C#.






    share|improve this answer














    In C#, the loop boundary condition is evaluated on each iteration. In VB.NET, it is only evaluated on entry to the loop.



    So, in the C# version in the question, because the length of stringValue is being changed in the loop, the final loop variable value will be changed.



    In VB.NET, the final condition is inclusive, so you would use <= instead of < in C#.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 2 days ago

























    answered 2 days ago









    Andrew Morton

    14.4k43047




    14.4k43047











    • Thanks for the reply. I now realise that using <= allows me to iterate and have the same output as the VB code. However, I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to. I'm going to update my question to show the same output.
      – slee423
      2 days ago










    • @slee423 The reason is given in the first sentence of my answer. Because the length of stringValue is being changed in the loop, the final loop variable value will be changed.
      – Andrew Morton
      2 days ago






    • 1




      apologies, thanks for that answer. And thanks for elaborating it in more detail for me.
      – slee423
      2 days ago






    • 1




      @slee423 I added that into the answer as it does indeed clarify it.
      – Andrew Morton
      2 days ago
















    • Thanks for the reply. I now realise that using <= allows me to iterate and have the same output as the VB code. However, I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to. I'm going to update my question to show the same output.
      – slee423
      2 days ago










    • @slee423 The reason is given in the first sentence of my answer. Because the length of stringValue is being changed in the loop, the final loop variable value will be changed.
      – Andrew Morton
      2 days ago






    • 1




      apologies, thanks for that answer. And thanks for elaborating it in more detail for me.
      – slee423
      2 days ago






    • 1




      @slee423 I added that into the answer as it does indeed clarify it.
      – Andrew Morton
      2 days ago















    Thanks for the reply. I now realise that using <= allows me to iterate and have the same output as the VB code. However, I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to. I'm going to update my question to show the same output.
    – slee423
    2 days ago




    Thanks for the reply. I now realise that using <= allows me to iterate and have the same output as the VB code. However, I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to. I'm going to update my question to show the same output.
    – slee423
    2 days ago












    @slee423 The reason is given in the first sentence of my answer. Because the length of stringValue is being changed in the loop, the final loop variable value will be changed.
    – Andrew Morton
    2 days ago




    @slee423 The reason is given in the first sentence of my answer. Because the length of stringValue is being changed in the loop, the final loop variable value will be changed.
    – Andrew Morton
    2 days ago




    1




    1




    apologies, thanks for that answer. And thanks for elaborating it in more detail for me.
    – slee423
    2 days ago




    apologies, thanks for that answer. And thanks for elaborating it in more detail for me.
    – slee423
    2 days ago




    1




    1




    @slee423 I added that into the answer as it does indeed clarify it.
    – Andrew Morton
    2 days ago




    @slee423 I added that into the answer as it does indeed clarify it.
    – Andrew Morton
    2 days ago












    up vote
    19
    down vote














    Now my question resolves around how VB differs to C# in terms of VB using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes.




    According to the VB.NET documentation:




    If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.




    So, the value of To 10 - stringValue.Length is evaluated once and reused until the loops exit.



    However, look at c#'s for statement




    If the for_condition is not present or if the evaluation yields true, control is transferred to the embedded statement. When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), the expressions of the for_iterator, if any, are evaluated in sequence, and then another iteration is performed, starting with evaluation of the for_condition in the step above.




    Which basically means that the condition ; i <= 10 - stringValueLength; is evaluated again each time.



    So, as you saw, if you want to replicate the code, you need to declare the final counter in c# before starting the loop.






    share|improve this answer
















    • 4




      The end condition evaluation has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
      – Andrew Morton
      2 days ago














    up vote
    19
    down vote














    Now my question resolves around how VB differs to C# in terms of VB using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes.




    According to the VB.NET documentation:




    If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.




    So, the value of To 10 - stringValue.Length is evaluated once and reused until the loops exit.



    However, look at c#'s for statement




    If the for_condition is not present or if the evaluation yields true, control is transferred to the embedded statement. When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), the expressions of the for_iterator, if any, are evaluated in sequence, and then another iteration is performed, starting with evaluation of the for_condition in the step above.




    Which basically means that the condition ; i <= 10 - stringValueLength; is evaluated again each time.



    So, as you saw, if you want to replicate the code, you need to declare the final counter in c# before starting the loop.






    share|improve this answer
















    • 4




      The end condition evaluation has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
      – Andrew Morton
      2 days ago












    up vote
    19
    down vote










    up vote
    19
    down vote










    Now my question resolves around how VB differs to C# in terms of VB using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes.




    According to the VB.NET documentation:




    If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.




    So, the value of To 10 - stringValue.Length is evaluated once and reused until the loops exit.



    However, look at c#'s for statement




    If the for_condition is not present or if the evaluation yields true, control is transferred to the embedded statement. When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), the expressions of the for_iterator, if any, are evaluated in sequence, and then another iteration is performed, starting with evaluation of the for_condition in the step above.




    Which basically means that the condition ; i <= 10 - stringValueLength; is evaluated again each time.



    So, as you saw, if you want to replicate the code, you need to declare the final counter in c# before starting the loop.






    share|improve this answer













    Now my question resolves around how VB differs to C# in terms of VB using the stringValue.Length condition in the for loop even though each time the loop occurs the length of the string changes.




    According to the VB.NET documentation:




    If you change the value of counter while inside a loop, your code might be more difficult to read and debug. Changing the value of start, end, or step doesn't affect the iteration values that were determined when the loop was first entered.




    So, the value of To 10 - stringValue.Length is evaluated once and reused until the loops exit.



    However, look at c#'s for statement




    If the for_condition is not present or if the evaluation yields true, control is transferred to the embedded statement. When and if control reaches the end point of the embedded statement (possibly from execution of a continue statement), the expressions of the for_iterator, if any, are evaluated in sequence, and then another iteration is performed, starting with evaluation of the for_condition in the step above.




    Which basically means that the condition ; i <= 10 - stringValueLength; is evaluated again each time.



    So, as you saw, if you want to replicate the code, you need to declare the final counter in c# before starting the loop.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered 2 days ago









    Camilo Terevinto

    16.3k63160




    16.3k63160







    • 4




      The end condition evaluation has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
      – Andrew Morton
      2 days ago












    • 4




      The end condition evaluation has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
      – Andrew Morton
      2 days ago







    4




    4




    The end condition evaluation has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
    – Andrew Morton
    2 days ago




    The end condition evaluation has the corollary that even if it doesn't vary but it is expensive to calculate, then it should be calculated just once before the loop.
    – Andrew Morton
    2 days ago










    up vote
    9
    down vote













    In order to make the example more understandable, I will convert both for loops into C# while loops.



    VB.NET



    string stringValue = "42";

    int min = 1;
    int max = 10 - stringValue.Length;
    int i = min;
    while (i <= max)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    C#



    string stringValue = "42";

    int i = 1;
    while (i <= 10 - stringValue.Length)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    The difference is then:




    VB.NET caches the maximum value for i, but C# recomputes it every time.







    share|improve this answer


















    • 2




      You don't need to convert loops to while
      – Panagiotis Kanavos
      2 days ago






    • 10




      It helped me to understand the for loops at my begins, I think they are much more understandable. This is why I 'translated' the examples in while loops, to help understanding.
      – Maxime Recuerda
      2 days ago














    up vote
    9
    down vote













    In order to make the example more understandable, I will convert both for loops into C# while loops.



    VB.NET



    string stringValue = "42";

    int min = 1;
    int max = 10 - stringValue.Length;
    int i = min;
    while (i <= max)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    C#



    string stringValue = "42";

    int i = 1;
    while (i <= 10 - stringValue.Length)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    The difference is then:




    VB.NET caches the maximum value for i, but C# recomputes it every time.







    share|improve this answer


















    • 2




      You don't need to convert loops to while
      – Panagiotis Kanavos
      2 days ago






    • 10




      It helped me to understand the for loops at my begins, I think they are much more understandable. This is why I 'translated' the examples in while loops, to help understanding.
      – Maxime Recuerda
      2 days ago












    up vote
    9
    down vote










    up vote
    9
    down vote









    In order to make the example more understandable, I will convert both for loops into C# while loops.



    VB.NET



    string stringValue = "42";

    int min = 1;
    int max = 10 - stringValue.Length;
    int i = min;
    while (i <= max)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    C#



    string stringValue = "42";

    int i = 1;
    while (i <= 10 - stringValue.Length)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    The difference is then:




    VB.NET caches the maximum value for i, but C# recomputes it every time.







    share|improve this answer














    In order to make the example more understandable, I will convert both for loops into C# while loops.



    VB.NET



    string stringValue = "42";

    int min = 1;
    int max = 10 - stringValue.Length;
    int i = min;
    while (i <= max)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    C#



    string stringValue = "42";

    int i = 1;
    while (i <= 10 - stringValue.Length)

    stringValue = stringValue + " " + stringValue.Length.ToString();
    Console.WriteLine(stringValue);
    i++;



    The difference is then:




    VB.NET caches the maximum value for i, but C# recomputes it every time.








    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited 20 hours ago









    camerondm9

    485715




    485715










    answered 2 days ago









    Maxime Recuerda

    26213




    26213







    • 2




      You don't need to convert loops to while
      – Panagiotis Kanavos
      2 days ago






    • 10




      It helped me to understand the for loops at my begins, I think they are much more understandable. This is why I 'translated' the examples in while loops, to help understanding.
      – Maxime Recuerda
      2 days ago












    • 2




      You don't need to convert loops to while
      – Panagiotis Kanavos
      2 days ago






    • 10




      It helped me to understand the for loops at my begins, I think they are much more understandable. This is why I 'translated' the examples in while loops, to help understanding.
      – Maxime Recuerda
      2 days ago







    2




    2




    You don't need to convert loops to while
    – Panagiotis Kanavos
    2 days ago




    You don't need to convert loops to while
    – Panagiotis Kanavos
    2 days ago




    10




    10




    It helped me to understand the for loops at my begins, I think they are much more understandable. This is why I 'translated' the examples in while loops, to help understanding.
    – Maxime Recuerda
    2 days ago




    It helped me to understand the for loops at my begins, I think they are much more understandable. This is why I 'translated' the examples in while loops, to help understanding.
    – Maxime Recuerda
    2 days ago










    up vote
    5
    down vote













    Because the for in VB is a different semantic than the for in C# (or any other C-like language)



    In VB, the for statement is specifically incrementing a counter from one value to another.



    In C, C++, C#, etc., the for statement simply evaluates three expressions:



    • The first expression is customarily an initialization

    • The second expression is evaluated at the start of each iteration to determine whether the terminal condition has been met

    • The third expression is evaluated at the end of each iteration, which is customarily an incrementer.

    In VB, you must supply a numeric variable which can be tested against a terminal value and incremented on each iteration



    In C, C++, C#, etc., the three expressions are minimally constrained; the conditional expression must evaluate to a true/false (or integer zero/non-zero in C, C++). You don't need to perform an initialization at all, you can iterate any type over any range of values, iterate a pointer or reference over a complex structure, or not iterate anything at all.



    So, in C#, etc., the condition expression must be fully evaluated on each iteration, but in VB, the terminal value of the iterator must be evaluated at the beginning, and need not be evaluated again.






    share|improve this answer


























      up vote
      5
      down vote













      Because the for in VB is a different semantic than the for in C# (or any other C-like language)



      In VB, the for statement is specifically incrementing a counter from one value to another.



      In C, C++, C#, etc., the for statement simply evaluates three expressions:



      • The first expression is customarily an initialization

      • The second expression is evaluated at the start of each iteration to determine whether the terminal condition has been met

      • The third expression is evaluated at the end of each iteration, which is customarily an incrementer.

      In VB, you must supply a numeric variable which can be tested against a terminal value and incremented on each iteration



      In C, C++, C#, etc., the three expressions are minimally constrained; the conditional expression must evaluate to a true/false (or integer zero/non-zero in C, C++). You don't need to perform an initialization at all, you can iterate any type over any range of values, iterate a pointer or reference over a complex structure, or not iterate anything at all.



      So, in C#, etc., the condition expression must be fully evaluated on each iteration, but in VB, the terminal value of the iterator must be evaluated at the beginning, and need not be evaluated again.






      share|improve this answer
























        up vote
        5
        down vote










        up vote
        5
        down vote









        Because the for in VB is a different semantic than the for in C# (or any other C-like language)



        In VB, the for statement is specifically incrementing a counter from one value to another.



        In C, C++, C#, etc., the for statement simply evaluates three expressions:



        • The first expression is customarily an initialization

        • The second expression is evaluated at the start of each iteration to determine whether the terminal condition has been met

        • The third expression is evaluated at the end of each iteration, which is customarily an incrementer.

        In VB, you must supply a numeric variable which can be tested against a terminal value and incremented on each iteration



        In C, C++, C#, etc., the three expressions are minimally constrained; the conditional expression must evaluate to a true/false (or integer zero/non-zero in C, C++). You don't need to perform an initialization at all, you can iterate any type over any range of values, iterate a pointer or reference over a complex structure, or not iterate anything at all.



        So, in C#, etc., the condition expression must be fully evaluated on each iteration, but in VB, the terminal value of the iterator must be evaluated at the beginning, and need not be evaluated again.






        share|improve this answer














        Because the for in VB is a different semantic than the for in C# (or any other C-like language)



        In VB, the for statement is specifically incrementing a counter from one value to another.



        In C, C++, C#, etc., the for statement simply evaluates three expressions:



        • The first expression is customarily an initialization

        • The second expression is evaluated at the start of each iteration to determine whether the terminal condition has been met

        • The third expression is evaluated at the end of each iteration, which is customarily an incrementer.

        In VB, you must supply a numeric variable which can be tested against a terminal value and incremented on each iteration



        In C, C++, C#, etc., the three expressions are minimally constrained; the conditional expression must evaluate to a true/false (or integer zero/non-zero in C, C++). You don't need to perform an initialization at all, you can iterate any type over any range of values, iterate a pointer or reference over a complex structure, or not iterate anything at all.



        So, in C#, etc., the condition expression must be fully evaluated on each iteration, but in VB, the terminal value of the iterator must be evaluated at the beginning, and need not be evaluated again.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited 13 hours ago

























        answered 2 days ago









        C Robinson

        1037




        1037




















            up vote
            -3
            down vote














            I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to.




            In VB, type the declaration is optional depending on the existence of the Option Explicit setting in the file.






            share|improve this answer






















            • The integer variable they’re referring to is stringValueLength.
              – Ry-♦
              yesterday














            up vote
            -3
            down vote














            I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to.




            In VB, type the declaration is optional depending on the existence of the Option Explicit setting in the file.






            share|improve this answer






















            • The integer variable they’re referring to is stringValueLength.
              – Ry-♦
              yesterday












            up vote
            -3
            down vote










            up vote
            -3
            down vote










            I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to.




            In VB, type the declaration is optional depending on the existence of the Option Explicit setting in the file.






            share|improve this answer















            I'm more interested in knowing as to why I've had to declare the integer variable and in VB I didn't have to.




            In VB, type the declaration is optional depending on the existence of the Option Explicit setting in the file.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited yesterday

























            answered yesterday









            Terry Carmen

            2,0571717




            2,0571717











            • The integer variable they’re referring to is stringValueLength.
              – Ry-♦
              yesterday
















            • The integer variable they’re referring to is stringValueLength.
              – Ry-♦
              yesterday















            The integer variable they’re referring to is stringValueLength.
            – Ry-♦
            yesterday




            The integer variable they’re referring to is stringValueLength.
            – Ry-♦
            yesterday

















             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f52607611%2fwhy-does-a-for-loop-behave-differently-when-migrating-vb-net-code-to-c%23new-answer', 'question_page');

            );

            Post as a guest













































































            Comments

            Popular posts from this blog

            Long meetings (6-7 hours a day): Being “babysat” by supervisor

            Is the Concept of Multiple Fantasy Races Scientifically Flawed? [closed]

            Confectionery