I am new to C # programming, I got a question about the exchange of variable values ​​without using the third one. With one solution, everything is clear:

int a = 2; int b = 4; a = a + b; b = a - b; a = a - b; 

I have another question, is it possible to somehow put it in the method? Posted by:

 class Program { public static void Main(string[] args) { Console.WriteLine("Введите значения переменных a и b"); Console.Write("a = "); int x = int.Parse(Console.ReadLine()); Console.Write("b = "); int y = int.Parse(Console.ReadLine()); SwapNumbers(x, y); Console.Write($"Переменная a = {x}, переменная b = {y} "); Console.ReadLine(); } public static void SwapNumbers(int a, int b) { a = a + b; b = a - b; a = a - b; } } 

But the variables x and y do not change places, at least in the Main method. You can do this:

 public static void SwapNumbers(int a, int b) { a = a + b; b = a - b; a = a - b; Console.Write($"Переменная a = {a}, переменная b = {b} "); } 

But it looks somehow clumsy and inappropriate, because I want the method to only swap the values ​​entered from the keyboard, and where and when I want to display them myself.

  • You forgot to specify the ref modifier to the parameters, so they are passed by value and have no effect on variables outside the method - Andrey NOP
  • four
    Well, in modern versions of the language, you can simply write: (x, y) = (y, x); - Andrew NOP
  • @ AndreiNOP as far as I know, in Sharpy it is only possible to do this through lambda, simply equating tuples will not work - kot_mapku3
  • @ kot_mapku3, I wouldn’t write if I wasn’t sure or didn’t check :) - Andrey NOP
  • @AndreyNOP but on rexter does not work, it gives an error. This is what version added? - kot_mapku3

4 answers 4

The thing is that you pass copies of variables to the Swap method. To be able to pass a link there is the keyword ref .

Those. the method will look like this:

 public static void Main(string[] args) { int a = 7, b = 5; Console.WriteLine("a -> {0}; b -> {1}", a, b); Swap(ref a, ref b); Console.WriteLine("a -> {0}; b -> {1}", a, b); } public static void Swap(ref int a, ref int b) { a = a + b; b = a - b; a = a - b; } 

There is also an out parameter. The difference between ref and out here: ref and out

  • And what do you mean transferring copies? That is, I kind of give the values ​​of these variables to the SwapNumbers method, in the Main method they remain the same, but the SwapNumbers method does not return changed values? - Alex Vause
  • @AlexVause, right. Some data types are referential, and some value types. For example, int and char value types, i.e. when passed to a method or somewhere else, exactly what is stored in the variable is transferred. But reference types (for example, class) are types that do not have a value, but the address of a place in memory (like the street address you live in. They can come to your address and live in your place instead of buying their home) . - kot_mapku3 1:06 pm

If you use the extreme version of the language C #, then you can get this mess

 int a = 10; int b = 15; Console.WriteLine($"{a}-{b}"); (a, b) = (b, a); // обмен Console.WriteLine($"{a}-{b}"); 

output expected

 10-15 15-10 

    When passing to a method by value (the default), a copy of the variable is passed to the method; accordingly, in your code, the x and y values ​​are not changed.

    When specifying the ref modifier, variables are passed to the method by reference, not by value. In this case, when the variable values ​​in the method change, the value in the calling method will also be changed.

       void Swap<T>(ref T a, ref T b){ T temp = a; a = b; b = temp; //Здесь <T> означает что будут использоваться неконкретные типы и мы эти типы и //будем менять местами. При вызове метода нужно использовать такой синтаксис //int a = 0, b = 1; //Swap(ref a,ref b) } 

      It is possible in sharp brackets (I do not know how to call them) enter the type of the variable and that's it.

      • one
        "I got a question about the exchange of variable values ​​without using the third ." And in the Main method, you will still have the old values ​​for x and y . - user218976
      • And why not use the third. Okay, sorry for the carelessness of my cant. - Aqua
      • In fact, the algorithm itself is not very important. At the moment I understand the topics of methods and scopes, so I just wanted to understand how to apply a specific method to the entered values. - Alex Vause
      • Swap<int>(ref a, ref b) - <int> , can be omitted, since the type is known to the compiler, based on the types a and b - Kir_Antipov