I have this small class looking like this:
private static int field1 = - 1;
private static int field2 = field1 + 1;
public static void Sum()
{
field1 = 10;
Debug.WriteLine(field2);
}
A call to Sum() writes '0'. Why?
Those aren't properties - they're fields. field2
is only related to field1
at initialization time - after that, they're completely independent fields. It's not like the field1 + 1
expression is re-evaluated every time field2
is read or every time field1
is written.
If you want field2
to just depend on the value of field1
, you should make it a property:
// Note: I wouldn't actually call this Field2, of course...
private static int Field2 { get { return field1 + 1; } }
This has happened because you are not updating prop2. You are only initialising it at the start.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With