Variable declared inside a for loop. How do I make this to a compile time error?

后端 未结 3 1847
南方客
南方客 2020-12-16 03:04

Today I investigated a logical bug in our software and figured out that this is related to the way VB.NET thread variables inside a loop.

Let\'s say I have the follo

3条回答
  •  天命终不由人
    2020-12-16 03:42

    Look at the code below. If not allowing a declaration without an initialization is a compiler error, then this code would not produce the correct output (a running total of even numbers). If you force me to initialize the value of 'total', then the method can never be correct.

    Dim numbers As New List(Of Integer) From {1, 2, 3, 4, 5, 6, 8, 9, 10}
    For Each number As Integer In numbers
    
        Dim total As Integer
    
        Dim isEven As Boolean = (number Mod 2 = 0)
    
        If isEven Then
            total += number
            Console.WriteLine("Running Total: {0}", total)
        End If
    Next
    

    Instead of adding an error, just fix the logic in the code. I don't see this as a particularly dangerous pitfall. Most programmers would be able to recognize this issue, and unit testing should also help to uncover these types of issues.

提交回复
热议问题