Skip to content

VB -> C#: Avoid loopTo in for loops if possible #1243

Open

Description

@circular17

Thanks for the wonderful tool. Here is an improvement that would make code conversion much easier.

When converting For loops from VB.NET to C#, if the final value of the range is not constant, a loopTo variable is added. While it makes sense from a semantic point of view, this makes the code slightly less readable.

If there are multiple for loops, we end up with a series of loopTo, loopTo2, loopTo3 etc. It would be wonderful if this could be simplified if possible.

For example, the following VB.NET code:

For i As Integer = 1 To n
Next

Is translated as:

for (int i = 1, loopTo = n; i <= loopTo; i++) { }

Proposed solution
When the upper bound is a local variable that is not explicited modified or passed as reference in the loop, simply use that variable instead of creating a duplicate. In the previous example, this would be:

for (int i = 1; i <= n; i++) { }

Another handy improvement would be when iterating from 0 to n - 1 when the loop variable is an integer.

For i As Integer = 0 To n - 1
Next

Would be translated using a strict comparison:

for (int i = 0; i < n; i++) { }

Activity

  1. changed the title [-]Avoid loopTo in for loops if possible (VB.NET to C#)[/-] [+]VB -> C#: Avoid loopTo in for loops if possible[/+] on Apr 6, 2026
  2. GrahamTheCoder commented on Apr 12, 2026

    @GrahamTheCoder
    Member

    Thanks. I'm happy to accept or help with PRs on this sort of thing. I agree that for a local variable it should be doable. The main two things to watch are.
    In other places where we detect data flow using a method IsNeverWrittenAsync semantic analysis. It's good but quite slow, and loops are common, so it may be necessary to provide a syntactic early exit that covers the common case. We'll need to keep safe underestimation - err on the side of correctness even if some loops still look ugly

  3. circular17 commented on Apr 12, 2026

    @circular17
    Author

    If I understand correctly, there is already a method to determine whether a variable is modified, but it is somewhat slow. I agree that, in the vast majority of cases, the variable is local, and it is trivial to check whether it is modified or could be modified when passed by reference. Indeed, it is reasonable to consider a variable as modified, for example, when it is passed by reference, even if in practice it is not. These are edge cases that should, in any case, be considered by the developer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions