Static variable

Devellopy

New member
Joined
Jul 25, 2021
Messages
4
Programming Experience
Beginner
Hi,

I've created a simplified code for this post :

C#:
public class Program
    {
        public static int value;
        public string printedValue = $"Value is {value}";

        public void printValue()
        {
            value = 3;
            Console.WriteLine(printedValue);
        }
    }

I would like my metod "printValue" returns "Value is 3" but it returns "Value is 0". So how can i change this ?

Thank you for your help.
 
Solution
You seem to be under the impression that printedValue should change when value does but that is not how it works. This:
C#:
$"Value is {value}"
is evaluated only once, when you assign the result to the printedValue field. It will use the current value of value at that time and changes to value that occur later will not affect that.

What you can do is use a property:
C#:
public string printedValue => $"Value is {value}";
That is shorthand for this:
C#:
public string printedValue
{
    get
    {
        return $"Value is {value}";
    }
}
That is effectively a method that gets evaluated each time you get the property value, so it will use the current value of value each time you do so.
You seem to be under the impression that printedValue should change when value does but that is not how it works. This:
C#:
$"Value is {value}"
is evaluated only once, when you assign the result to the printedValue field. It will use the current value of value at that time and changes to value that occur later will not affect that.

What you can do is use a property:
C#:
public string printedValue => $"Value is {value}";
That is shorthand for this:
C#:
public string printedValue
{
    get
    {
        return $"Value is {value}";
    }
}
That is effectively a method that gets evaluated each time you get the property value, so it will use the current value of value each time you do so.
 
Solution

Latest posts

Back
Top Bottom