Search code examples
vb.netreturn-valueassignment-operator

What is the return value of an assignment in vb.net?


What's the return value when I do an assignment?

For example, can I do this? (i.e. the assignment returns the value being assigned)

Dim a As Integer = 1
Dim b As Integer = 2
a = b = 3

The question came up when I wrote this code today:

Dim updates = GetUpdates()
While updates.Count > 0
    Foo.ApplyUpdates(updates)
    updates = GetUpdates()
End While

I kind of wish I could have written it this way...

While (updates = GetUpdates).Count > 0
    Foo.ApplyUpdates(updates)
End While

I know it's not as clean... (and I totally never declared updates) but it got me curious about how assignments work in .NET... is it a function with a return value? If so... what does it return?

Edit

I gave the first chunk of code a try. It looks like the compiler interprets it as assigning the result of comparing b and 3 to a... which is a compiler error of course.

And for the second code chunk, I get that the operator = is not defined for what ever type updates is... i.e. it thinks it's a comparison, not an assignment.

So to add to my question, why does it work this way? Is it just because vb.net overloads the symbol = with two meanings (assignment and comparison)?


Solution

  • about how assignment working in .NET.

    This is actually about how assignment works in VB, not in .NET.

    This does not work in VB.Net. The = Operator in VB.Net merely "assigns the value on its right to the variable or property on its left."

    What's the return value when I do an assignment?

    As seen in the above statement, the assignment operator does not return a value in VB.Net.

    Note that this differs from other .NET languages. For example, in C#, the assignment = Operator does what you're describing, and "stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result."

    Dim a As Integer
    Dim b As Integer
    a = b = 3
    

    Note that, with Option Strict specified, this will actually be an error: "Option Strict On disallows implicit conversions from 'Boolean' to 'Integer'."

    This is because VB.Net sees this as two operations - it's basically trying to do:

    Dim a As Integer
    Dim b As Integer
    
    Dim temp as Boolean
    temp = (b = 3)
    a = temp
    

    So to add to my question, why does it work this way? Is it just because vb.net overloads the symbol = with two meanings (assignment and comparison)?

    Well, it's how the language was designed. I suspect that you are correct, though, and since the same operator (=) is used as an assignment and a comparison is why VB was made this way. However, the original VB language was this way, and to keep the syntax for VB.Net the same (or as close as possible), I suspect this behavior was carried forward.