The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  75 Posts :: 0 Stories :: 49 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

After doing some random surfing this morning (I think I started off with binging “operator precedence C#”, I landed on this page about one line variable swaps, which then got me thinking about how to do this in C#. My only solution I could come up with was using arithmetic to solve the problem:

 

int x = 11;
int y = 42;
 
y = (y + x) - (x = (y + x) - x);
 
Debug.Assert(x == 42);
Debug.Assert(y == 11);

 

Please don't use this code, unless you're on some type of job security mission :)

 UPDATE: 12 Aug 2009 – Ok, so I wasted more time on it. Savage also submitted a refactored version of my previous try

 

int x = 11;
int y = 42;
 
x = y ^ x ^ (y = x);
 
Debug.Assert(x == 42);
Debug.Assert(y == 11);

 

posted on Thursday, August 06, 2009 6:55 AM

Feedback

# re: One-line integer swap in C# 8/11/2009 12:00 PM Savage
Nice one!

# re: One-line integer swap in C# 8/12/2009 8:18 AM Savage
Or we could simplify it to:

y = (x + y) - (x = y);

I believe thats 1 All

# re: One-line integer swap in C# 8/12/2009 8:19 AM Darksider
Wicked indeed :)

Comments have been closed on this topic.