CodeConverter icon indicating copy to clipboard operation
CodeConverter copied to clipboard

VB -> C#: Local variables should be pulled before labels

Open Yozer opened this issue 3 years ago • 3 comments

VB.Net input code

Public Shared Sub Main()
    Label:
    Dim number As Integer
    number += 1
    If number = 1 Then GoTo Label
        
    Console.WriteLine(number) ' will print 2
End Sub

Erroneous output

public static void Main()
{
Label:
    ; // that's ugly but still compiles
    var number = default(int);
    number += 1;
    if (number == 1)
        goto Label;

    Console.WriteLine(number);  // will never be called, infinite loop
}

Expected output

public static void Main()
{
    var number = default(int);
Label:
    number += 1;
    if (number == 1)
        goto Label;

    Console.WriteLine(number); 
}

Details

  • Product in use: e.g. codeconverter.icsharpcode.net / VS extension / both
  • Version in use: e.g. 5.6.3 or a commit hash https://github.com/icsharpcode/CodeConverter/commit/73d55b29c6c1e09dd9e3b6e9b30073d639d9e00d
  • Did you see it working in a previous version, which? no
  • Any other relevant information to the issue, or your interest in contributing a fix.

Very rare but unfortunately possible to happen in large, legacy code bases. Maybe every variable initialization should be moved to the beginning of the procedure/before all labels when there are goto statements? Related to #897

Even if the scope of a variable is limited to a block, its lifetime is still that of the entire procedure. If you enter the block more than once during the procedure, each block variable retains its previous value. To avoid unexpected results in such a case, it is wise to initialize block variables at the beginning of the block.

Yozer avatar Jun 29 '22 14:06 Yozer

I think most people don't put labels in their code, so a special case when they're present to pull declarations before the first label seems sensible.

GrahamTheCoder avatar Jun 30 '22 17:06 GrahamTheCoder

I think most people don't put labels in their code

There are a lot of them in 20 years old code ;)

But I never had infinite loop when using CodeConverter tool

Saibamen avatar Jul 06 '22 12:07 Saibamen

I think most people don't put labels in their code

There are a lot of them in 20 years old code ;)

But I never had infinite loop when using CodeConverter tool

I think that infinite loop is just one of the possible symptoms so if have a lot of labels I would be careful. For example this prints 2 in VB but converted code will print 1.

Yozer avatar Jul 06 '22 15:07 Yozer