A way to swap variables?

Does VB provide an easy way to swap the contents of 2 variables without having to use an intermediate variable Thanks...



Answer this question

A way to swap variables?

  • Vestra

    x ^= y;
    y ^= x;
    x ^= y;
    will swap x and y.

    That's in C#.  Not sure how to do the exclusive-or operator in VB.  I'm sure someone else does though.


  • G.G.

    hi,

    once i saw a blog did that in C# using binary shifting operators but unfortunatly i don't remember the link

    best regards



  • smo5024

    Well I made a quick function that works fine for me...

    Public Sub Swap(ByRef x, ByRef y)

    xx = y : yy = x

    x = xx : y = yy

    End Sub

    That works fine for me xD Hope this helped :P



  • alois paulin

    In VB you can define your own functions.
  • ErwinTsai

    Dang I was wondering the same thing, cause I used it in c++ sometimes lol, o well xD

  • robepstein

    It is VB so it must be Xor. :)



  • jaypatel

    No, not that I know of,

    you'll need to write a simple function to do that.


  • Johan Andersson

    I was really hoping for a Swap(x,y) command or something similar. I seem to recall other languages having this functionality.


  • David Anton

    Use a stack!

    Dim x As Integer = 1

    Dim y As Integer = 9

    Dim myStack As New Stack()

    myStack.Push(x)

    myStack.Push(y)

    x = myStack.Pop()

    y = myStack.Pop

    MsgBox("x, dim'ed as 1 is now " & x)

    MsgBox("y, dim'ed as 9 is now " & y)



  • A way to swap variables?