People may sound silly but I can’t understand why it doesn’t work

class Program { static void Main(string[] args) { while (true) { Console.Write("Введите сумму: "); int enterSum = Convert.ToInt32(Console.ReadLine()); int s = enterSum; int r = 0; MethodCall(s, ref r); BLogic bLogic = new BLogic(); bLogic.MethodResult(s, r); } } public static int MethodCall(int sum, ref int result) { if (result != null) { return result += sum; } return sum; } } ___________________________________________________________ class BLogic { private int _sum { get; set; } private int _result { get; set; } public BLogic() { } public void MethodResult(int sum, int result) { _sum = sum; _result = result; DateTime date = DateTime.Now; Console.WriteLine($"Сумма {_sum} | Результат = {_result} | Дата внесения = {date}"); } } 

Here is the code.
Need to? so that at each subsequent iteration of the loop the result becomes (sum + = result), that is, the entered sum (for example, 500) is added to the result (which is 0 at the first iteration, that is, the result is 500). And, at the next iteration, the result that was 500 + the number entered (for example, 1000) and that result is already 1500. It seems that it just doesn't work anyway.
The result is always (sum 500 and result 500) at the next iteration (sum 1000 and result 1000) well, I can’t understand why. Explain, please.

Tried and without (ref) the result is the same.

  • You re-initialize the variables at each loop iteration. You need to move them out of the cycle - until while true - AK
  • @AK Thanks for the reply! - j. Atisto

1 answer 1

There is no need for transmissions by reference here, just store the data out of the loop. You also have a lot of unnecessary initializations.

 static void Main(string[] args) { int result = 0; BLogic bLogic = new BLogic(); while (true) { Console.Write("Введите сумму: "); bool ok = int.TryParse(Console.ReadLine(), out var value); if (ok) { result += value; bLogic.MethodResult(result, value); } else { Console.WriteLine("Введено некорректное значение"); } } } 
  • It works, thanks! - j. Atisto
  • And, could you explain this line to me => bool ok = int.TryParse(Console.ReadLine(), out var value); I understand that bool = ok assigned the value true if something is entered a, the value passed to the value variable. I understood correctly? If not then could not explain. - j. Atisto
  • @ j.Atisto method translates a string into an integer, if the transfer is successful - returns true , if not successful, then false , writes the translation result to value The string from which we are trying to pull a number is the first argument of the method. - yolosora
  • Thank you clear! - j. Atisto