C# Triple XOR: swapping two variables without a temporary variable

Swapping two variable values without using a temporary variable can be accomplished by using a triple XOR.

This is a little hack or trick that was used in the past but which is a bit obsolete now. The compiler is normally smart enough to optimize your temporary variable code.

Note that this code can give you bad results (might give you different result when using i.e. floats)

using System;

namespace ConsoleApplication1
{
 class Program
 {
   static void Main(string[] args)
   {
     Console.WriteLine(string.Format("Result: {0}", Class1.WriteReverse("The quick brown fox jumps over the lazy dog.")));
     Console.ReadLine();
   }
 }

 public class Class1
 {
   public static string WriteReverse(string s)
   {
     if (string.IsNullOrEmpty(s)) return "Not valid";

     char[] c = s.ToCharArray();
     int j = s.Length - 1;

     for (int i = 0; i < j; i++, j--)
     {
       c[i] ^= c[j];
       c[j] ^= c[i];
       c[i] ^= c[j];
     }

     return new string(c);
   }
 }
}

 

Note that I also used multiple statements in the for-loop. (see highlighted line)

Have fun! 😉

Advertisements

Remove and sort using statements

A lot of people don’t know this but you can actually clean up your using statements in your Visual Studio projects almost automatically.

In case you didn’t know, here is how to do it:

You have a big list of using statements in your class. It might look like this by default:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

Just do a right-mouse click on the using statements and select:
[Organize Usings] > [Remove and Sort].

This will remove all the unnecessary and unused usings. The result might look as clean as this:

using System.Windows.Controls;

Sometimes, nothing could be removed or sorted but in most new class files there are a lot of default usings. It might be good to clean them once in a while, especially if you wrote and removed lots of (test) code in a class.

Happy programming 😉