VB -> C#: variable is initialized inside loop
See original GitHub issueVB.Net input code
Private Shared Sub DefaultInitialization()
For i = 1 To 2
Dim b As Boolean
If i = 1 Then
Assert.That(Not b)
Else
Assert.That(b)
End If
b = True
Assert.That(b)
Next
End Sub
Erroneous output
private static void DefaultInitialization()
{
for (int i = 1; i <= 2; i++)
{
var b = default(bool);
if (i == 1)
{
Assert.That(!b);
}
else
{
Assert.That(b);
}
b = true;
Assert.That(b);
}
}
Expected output
private static void DefaultInitialization()
{
var b = default(bool); // define and initialize outside loop or do not initialize (with compile error CS0165)
for (int i = 1; i <= 2; i++)
{
// bool b;
if (i == 1)
{
Assert.That(!b);
}
else
{
Assert.That(b);
}
b = true;
Assert.That(b);
}
}
Details
- Product in use: VS extension
- Version in use: 9.0.0.0
- Did you see it working in a previous version, which? no
Issue Analytics
- State:
- Created a year ago
- Comments:7 (6 by maintainers)
Top Results From Across the Web
vb.net - Variable declared inside a for loop. How do I make ...
In VB.NET, a variable that is declared inside a for loop keeps its value for the next itaration. This is by design: http://social.msdn.microsoft ......
Read more >Variable declarations in loops should have explicit ...
The variable is only implicitly initialized when allocating its memory for the first time and keeps the its current value into the next ......
Read more >Why is it that variables declared within a for loop lose their ...
1. Narrowed Scope - The variable declared inside a while loop is scoped to that loop. This protects it from being altered by...
Read more >Is it necessary to initialize a variable under the while loop
Variable initialization means that you must store a value in the variable before any attempt to use its contain. C++. while(i = 0...
Read more >Is it a bad programming practice to declare variable in ...
short answer: In VB6 I think it's best to declare just before the loop. This is mostly so that nobody thinks that the...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Sounds like another job for PerScopeState / IHoistedNode
VB still manages to surprise me after all these years. If I ever knew about that “feature” of VB (pulling the variable into the outer scope), I’ve erased it from my mind. I guess it’s because VB only allows one loop variable but you might want multiple, and there’s no other way to limit the scope to within the loop since blocks don’t exist. Whatever the reason, yep it definitely needs fixing in the converter!