Mike sends us some VB.Net code today.
For fileDataCount = 0 To 4 Step 1 Try Dim dataValidate As String = fileData(fileDataCount).ToString Catch ex As Exception error = 1 End Try Next
We enter a loop from 0 to 4, counting by 1. We don't need to specify that, that's the default behavior, but hey, it doesn't hurt to be explicit. Then, in a
try/catch, we create a string variable and try and extract an element from the array via the loop counter. If this fails, we set an error flag and keep looping.
The question is: what is this code for? It sets the
error flag under two conditions: if an element in the array is null (
ToString will fail), or if the array doesn't contain 5 elements.
The validation, in this case, wasn't concerned about nulls: they were just using this block of code to check the array length. Worse, it's technically incorrect, as the array should contain exactly five elements, and this code only checks that it contains at least five elements.
There is, of course, a much simpler way to solve the problem in question:
if fileData.Length <> 5, we have an error. And yes,
<> is the inequality operator in VB.
This post originally appeared on The Daily WTF.