Vladimir Khodakovskey Vladimir Khodakovskey - 1 year ago 89
C# Question

How to swap values of two string variables without a temp variable?

For example, I have two string variables:

string a = " Hello ";
string b = " World "

How can I swap it without a temporary variable?

I found an example, but it used a third variable for the length of

int len1 = a.Length;
a = a + b;
b = a.Substring(0, len1);
a = a.Substring(len1);

How can I do that?

Answer Source

You can use SubString without using a temp variable, like this:

string a = " Hello ";
string b = " World ";

a = a + b;//" Hello  World "
b = a.Substring(0, (a.Length - b.Length));//" Hello "
a = a.Substring(b.Length);//" World "
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download