Home >Backend Development >C#.Net Tutorial >Swapping two variables in one line using C#
To swap two variables in a single line using the Bitwise XOR Operator.
val1 = val1 ^ val2 ^ (val2 = val1);
Above, we have set the values −
int val1 = 30; int val2 = 60;
The following are Example of swapping variables using one line of code in C#:
using System; class Demo { public static void Main(String[] args) { int val1 = 30; int val2 = 60; Console.WriteLine("Values before swap"); Console.WriteLine(val1); Console.WriteLine(val2); val1 = val1 ^ val2 ^ (val2 = val1); Console.WriteLine("Values after swap"); Console.WriteLine(val1); Console.WriteLine(val2); } }
The above is the detailed content of Swapping two variables in one line using C#. For more information, please follow other related articles on the PHP Chinese website!