Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does = perform comparison instead of assignment?

Tags:

vb.net

In VB.NET, there's no == operator for comparison, so the = operator serves that purpose as well as assignment. I have a function, and I want it to return the boolean result of a comparison, without storing that result in a variable:

Private Function foo() As Boolean
    Dim bar As Integer = 1
    Return bar = 2
End Function

Returns: False

OK, but what's the value of bar?

Private Function foo() As KeyValuePair(Of Boolean, Integer)
    Dim bar As Integer = 1
    Return New KeyValuePair(Of Boolean, Integer)(bar = 2, bar)
End Function

Returns: False, 1

It looks like = will perform a comparison when the statement context demands it, but is this guaranteed? That is, can I be sure that bar will never be set to 2 in this situation?

Also, I know that VB.NET doesn't allow chained inline assignments, which may be for the best. Does this odd = behavior cause any other quirks I should be aware of?

like image 239
Jack Avatar asked Feb 14 '23 23:02

Jack


1 Answers

You cannot do in-line assignments in VB, Assignment is an explicit statement:

[Let] <<target-reference>> = <<value-expression>>

The Let is optional and implicit, and hardly ever used anymore. The general rule that you can use to distinguish the [Let] command from equality testing is that for Let, no other keyword may come before the target-reference in the statement. AFAIK, in all cases of = as equality testing, there is one or more other keywords that precede it in the statement.

In your first example, the keyword Return precedes your =, so it's an equality test, and not an assignment.

In your first example you can do either:

Return 2

or

bar = 2
Return bar

As for your question "OK, but what's the value of bar?", bar still equals one.

= in VB cause no quirks. It works exactly as documented, and it always has (including its predecessor, BASIC back to 1968).

like image 109
RBarryYoung Avatar answered Feb 26 '23 10:02

RBarryYoung