0

So, hypothetically, if I were to be trying to write a sort-of "GetMax" function between two numbers, and I wanted to return the largest of the two by reference, so I could edit said returned reference variable directly from the calling of the function.

So in CPP it could look like this:

int& GetMax(int& a, int& b)
{
    if (a > b) {
        return a;
    }
    else {
        return b;
    }
}

And I could edit it like this:

int main(void)
{
    int a = 30;
    int b = 20;

    GetMax(a, b) = 10;

}

GetMax(a, b) = 10; Would change a's value.

Would I be able to do something similar in Visual Basic?

Function GetMax(ByRef a As Integer, ByRef b As Integer) As Integer

    If a > b Then
        Return a
    Else
        Return b
    End If

End Function

^ But instead of returning a value, it would return a reference, so I could treat the function the same way I did in the CPP example. I haven't really dedicated myself to learning visual basic, so I don't really know if I'm completely missing a key concept that would allow me to do the thing that I wish. Thank you ! :)

2 Answers 2

1

The answer is no, so you'd have to do something like this to get the same result in the example you provided:

Sub SetMax(ByRef a As Integer, ByRef b As Integer, value As Integer)

    If a > b Then
        a = value
    Else
        b = value
    End If

End Sub

and call:

SetMax(a, b, 10)
Sign up to request clarification or add additional context in comments.

Comments

0

The problem is that VB.NET doesn't want you to program cpp style. So while complex objects will always be references, primaries aren't. If you wanted to edit a primary in a sub you could put ByRef myVariable as Integer (or any other primary type) in your overload and it would work as a reference, but you won't be able to return it as a reference.

With complex objects, no problem. With primaries, forget that.

C# could do it, though, if it's the same to you.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.