C # Challenge Exchange Variable Values

1

Recently I made a very simple challenge:

  

Change the value of two variables without using a third variable.

int a = 5;
int b = 3;

a += b;     // a = 8
b = a - b;  // b = 5;
a -= b;     // a = 3;

It is simple because they are arithmetic operations.

But I was wondering how to do it if they were strings .

string a = 'Stack';
string b = 'Overflow';

I've even thought of some solutions, but these apply to #

Example JS

var a = 'Stack';
var b = 'Overflow';

a = a+'|'+b;      // a = 'Stack|Overflow';
a = a.split('|'); // a = ['Stack', 'Overflow'];

b = a[0];  // b = 'Stack';
a = a[1];  // a = 'Overflow';

How could you solve this challenge with string ?

    
asked by anonymous 20.01.2016 / 13:42

2 answers

2

There are several ways to do it.

What I first thought was

string a = "Teste";
string b = "Overflow";

a += "|" + b;

b = a.Split('|')[0];
a = a.Split('|')[1];

WriteLine($"a = {a} - b = {b}");

The output will be:

  

a = Overflow - b = Test

See working at .NET Fiddle

    
20.01.2016 / 13:48
1

Following exactly the same idea as jbueno, but using the weak typing language artifacts, where in C # you can achieve these advantages with dynamic.

dynamic a = "Teste";
string b = "Overflow";

a = (a + "|" + b).Split('|');

b = a[0];
a = a[1];

WriteLine($"a = {a} - b = {b}")
    
21.01.2016 / 16:12