Today I challenged myself to make a simple math application in a language I do not know (VB). Coming from C# I thought it would be quick however I'm wrong to say the least.
What I'm trying to do is calculate the two values a user enters in real time in the inputAlpha and inputBeta text boxes and display the Sum/Difference/Average/etc in the respective label boxes to the right of the labels you do see. At the moment I'm at an impass with two problems. One is the sumOutput.Content is not showing the sum whether the local variable sum is a Integer or a String. The second is the math isn't actually adding 10+10 rather it is just combining the two to 1010. I understand this is probably trivial to 99% of you but I'm here to learn from my mistakes so I thank you for any feedback.
First issue:
This wouldn't work properly in C#, either.
In VB, like C#, the +
operator does double-duty. It can either perform math or concatenate strings. Since you are using the Text
property on both sides, you have String + String
which will concatenate the strings. If you want to do math, you need to convert the values to numbers first. For example, you could:
Dim left As Integer = Integer.Parse(inputAlphaTextBox.Text)
Dim right As Integer = Integer.Parse(inputBetaTextBox.Text)
Dim sum As Integer = left + right
Second issue:
VB doesn't have a separate assignment operator (=
) and equality operator (==
) like C# does. It uses the symbol =
for both assignment and equality and uses context to decide which one it needs.
Since you are using Return
, it assumes there is an expression on the right-hand side. That expression is sumOutput.Content = sum.ToString()
. Since it is expecting an expression, when it decides how to interpret the =
operator, it chooses equality. So it's trying to return True
or False
.
This is where it gets weird and I'm making a little bit of a guess.
Your function returns Integer
, but that's a Boolean
. So why aren't you getting a compile error? I'm going to take a wild guess and assume you haven't changed the defaults, so Option Strict
is off. This allows VB to make some type conversions that you might not expect. IIRC, False
will convert to the integer 0
and True
will convert to the Integer 1
.
This code, as written, would be poor practice even in C#. It should really be written like:
Private Sub DoMath()
Dim left As Integer = Integer.Parse(inputAlphaTextBox.Text)
Dim right As Integer = Integer.Parse(inputBetaTextBox.Text)
Dim sum As Integer = left + right
subOutput.Content = sum.ToString()
End Sub
There's nothing to return and the call site doesn't expect one, so it should have no return value. In C# that's a void
function, in VB that's a Sub
. Removing the Return
statement helps VB understand you want to perform an assignment, not make a comparison.