3 Replies - 4058 Views - Last Post: 18 October 2010 - 06:56 AM Rate Topic: -----

#1 DanDeCoder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 30
  • Joined: 18-October 10

Code to swap values between two variables.

Posted 18 October 2010 - 02:34 AM

Hi Guys,
I'm relatively new to C# programming and am still trying to find my feet a little. I need a hand with creating a program that can swap the values between two integer variables. I've set them to two fixed values, ie: priceOne and priceTwo, however I would like to be able to run a program that can swap these variables..
Any help is appreciated.
Is This A Good Question/Topic? 0
  • +

Replies To: Code to swap values between two variables.

#2 Rico Diesel  Icon User is offline

  • D.I.C Head

Reputation: 62
  • View blog
  • Posts: 122
  • Joined: 06-May 10

Re: Code to swap values between two variables.

Posted 18 October 2010 - 02:41 AM

Maybe this will help: same question at Stack Overflow
Was This Post Helpful? 2
  • +
  • -

#3 JustinDe  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 58
  • Joined: 24-September 10

Re: Code to swap values between two variables.

Posted 18 October 2010 - 04:14 AM

Another way you might want to look at doing this is creating a temporary variable.

Imagine having 2 glasses of water and wanting to keep the contents separate. You need to dump one of them into a third container to be able to trade glasses.

x = 1;
y = 2;
z;

z = x;
x = y;
y = z;
z = 0; (just clearing z)

end result------
x = 2
y = 1
z = 0
Was This Post Helpful? 0
  • +
  • -

#4 Curtis Rutland  Icon User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 4576
  • View blog
  • Posts: 8,018
  • Joined: 08-June 10

Re: Code to swap values between two variables.

Posted 18 October 2010 - 06:56 AM

As the second answer at the linked SO thread said, the best way to do it is simply create a third, temporary variable.

All the other ways in most contexts are just showing off. Yes, you can do a little math to swap numeric values in place. No, you probably shouldn't, because it's neither intuitive or necessary in the vast majority of cases. Unless you're working on the most memory-intensive of applications, you'll never feel that extra int/double.

The only use for this skill is interview questions or homework problems.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1