How to swap two variables in C#?
i.e.:
var a = 123;
var b = "hello!";
swap(a, b); // hypothetical
System.Console.WriteLine(a);
System.Console.WriteLine(b);
outputs:
hello!
123
How to swap two variables in C#?
i.e.:
var a = 123;
var b = "hello!";
swap(a, b); // hypothetical
System.Console.WriteLine(a);
System.Console.WriteLine(b);
outputs:
hello!
123
You cannot do it with variables of different type. When the variables are of the same type, the simplest way is the "naive" implementation with a temp
:
var temp = a;
a = b;
b = temp;
You can wrap this into a swap
method that takes its parameters by reference:
static void Swap<T>(ref T a, ref T b) {
var temp = a;
a = b;
b = temp;
}
You cannot change the type of a statically typed variable (var
uses a static type determined at compile time). You can declare your variable as object
or dynamic
if the type of a variable must change at runtime. In case you do it, however, the value types (including int
s) will be wrapped in reference types.
You can't do that with var
.
If you really needed to do something like that, you could use dynamic
and your typical implementation of a swap with temp:
dynamic a = 123;
dynamic b = "hello!";
var temp = a;
a = b;
b = temp;
object varA = 123;
object varB = "hello!";
object temp = varA;
varA = varB;
varB = temp;
That should work with different types for all .NET versions (I think).