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.
refmodifier to the parameters, so they are passed by value and have no effect on variables outside the method - Andrey NOP(x, y) = (y, x);- Andrew NOP