C#: Generic swap functions

This entry is part 70 of 71 in the series C#

Generic swap functions

namespace Test
{
	class Program
	{
		
		public static void Swap<T> (T a, T b)
		{
			var temp = a;
			a = b;
			b = temp;
		}

		public static void Swap<T> (ref T a, ref T b)
		{
			var temp = a;
			a = b;
			b = temp;
		}

		public static void SwapValue (SwapTest a, SwapTest b)
		{
			var temp = a.Value;
			a.Value = b.Value;
			b.Value = temp;
		}

		public class SwapTest
		{
			public string Value { get; set; }
		}

		static void Main ()
		{
			var a = new SwapTest { Value = "a" };
			var b = new SwapTest { Value = "b" };
			Swap (a, b);
			Console.WriteLine ("Value a: " + a.Value + " |  Value b: " + b.Value); 
			//output: Value a : a | Value b : b  

			a = new SwapTest { Value = "a" };
			b = new SwapTest { Value = "b" };
			Swap (ref a, ref b);
			Console.WriteLine ("Ref Value a: " + a.Value + " |  Ref Value b: " + b.Value); 
			//output: Ref Value a : b | Ref Value b : a 

			a = new SwapTest { Value = "a" };
			b = new SwapTest { Value = "b" };
			SwapValue (a, b);
			Console.WriteLine ("Swap Value a: " + a.Value + " |  Swap Value b: " + b.Value); 
			//output: Swap Value a : b | Swap Value b : a 
			Console.Read ();
		}
	}
}

swap

Series Navigation<< C#: Enumeration
C#: Get and Set >>