0

Goal:

I am having some issues in C# when ensuring that a variable retains its assigned value for the duration / runtime of a program. In particular, I am attempting to:

  1. Read a number in from some input
  2. Save it to a variable of type double
  3. Print the variable
  4. Ensure that this value stays the same for the duration of the program, so that on the next iteration when a new value is read in, the previous value from step (2) is still printed.

I have attempted to use a global static variable such as public static double foo;, however, each iteration of the program produced a new value.

In C, for example, I believe the closest functionality to this would be to use the static keyword, however, I have read that this functionality has been intentionally excluded from C# and I am struggling to learn why this is the case.

void foo()
{
     static int j;
     int i = calculateSomeValue() + j;
     j = i;
}

Please note that before deciding to post this question, I have consulted the following resources:

  1. https://softwareengineering.stackexchange.com/questions/141871/false-friends-keyword-static-in-c-compared-to-c-c-and-java
  2. https://docs.microsoft.com/en-us/answers/questions/240965/retain-previous-value-of-text-box-till-the-form-is.html
  3. Retain local variable across method calls
  4. How to retain old value when setting variable on c# class
  5. https://social.msdn.microsoft.com/Forums/en-US/46243c7b-959e-4753-a173-34f52a7f8922/variables-retain-value-from-first-pass?forum=csharpgeneral

Q1. How can a value assigned to a variable be retained for the entire runtime of a 'C#' program?

Apologies if I am missing something extremely obvious, but it seems that the static keyword in C is used in a different manner compared to that of C#.

p.luck
  • 524
  • 2
  • 6
  • 29

0 Answers0