Skip to content

Instantly share code, notes, and snippets.

@CallumWatkins
Last active February 18, 2017 16:32
Show Gist options
  • Save CallumWatkins/c6a390e0278a875d35375b130a672a03 to your computer and use it in GitHub Desktop.
Save CallumWatkins/c6a390e0278a875d35375b130a672a03 to your computer and use it in GitHub Desktop.
A generic method for swapping two variables, the type of which implements IEquatable<>, if both variables are not equal. License: MIT
/// <summary>
/// Swaps two variables of type T with one another.
/// </summary>
/// <typeparam name="T">The type of both variables. Must implement IEquatable.</typeparam>
/// <param name="a">The first variable.</param>
/// <param name="b">The second variable.</param>
static void Swap<T>(ref T a, ref T b) where T : IEquatable<T>
{
if (a.Equals(b)) return;
T tempA = a;
a = b;
b = tempA;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment