I am currently working on converting some VB source code over to C#. While I understand there are converters to automate this, and that I could actually use this particular dll without rewriting it, I'm doing it partially so I can understand VB better. Not so much as to expect to write it, but it's at least helping me to be able to read it.
In doing this though, I've come across something that is quite confusing. The following code snippets are examples, but I've seen it throughout the program.
VB Source Code:
Friend Function AllocateObjectNumber() As Long
AllocateObjectNumber = _nextFreeObjectNumber
_nextFreeObjectNumber += 1
_objectAllocatedCount += 1
End Function
My translated C# Code:
internal long AllocateObjectNumber()
{
cvNextFreeObjectNumber += 1;
cvObjectAllocatedCount += 1;
return cvNextFreeObjectNumber;
}
What I'm not understanding is the flow control that VB uses. I understand that AllocateObjectNumber += 1
is used in place of return cvNextFreeObjectNumber
, but if this line comes before the incrementing of the two variables, then how is that code not considered unreachable? Based on my C# understanding, the first line in this method would immediately return to the calling method, and this whole method would basically act as a pseudo-Property.
Any helpful explanations?
The VB approach is more similar to storing the value in a temporary variable:
internal long AllocateObjectNumber()
{
var nextNumber = _nextFreeObjectNumber
cvNextFreeObjectNumber += 1;
cvObjectAllocatedCount += 1;
return nextNumber;
}
In VB the function = value
syntax doesn't do a return
- so the code after can keep running. When that method reaches the end, then the value you used becomes the 'return' value for whatever called it in the first place.
You can use the function = value
syntax multiple times in the same method as a way of returning a different result in different conditions without needing the temporary variable I used in my example.
Based on my C# understanding, the first line in this method would immediately return to the calling method
But it’s not C# code, it’s VB code. AllocateObjectNumber = _nextFreeObjectNumber
does not return, it just assigns a return value. The actual return is at the end of the method.
Most people would actually write the VB code identical to the C# code, i.e. using Return
explicitly. The assign-to-method-name style is a remnant of older VB versions where it was the only way of returning a value from a function. In VB.NET, you can use both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With