Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum of static properties not correct

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?

like image 803
user1151923 Avatar asked Dec 12 '22 01:12

user1151923


2 Answers

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; } }
like image 51
Jon Skeet Avatar answered Dec 31 '22 06:12

Jon Skeet


This has happened because you are not updating prop2. You are only initialising it at the start.

like image 39
Gaz Winter Avatar answered Dec 31 '22 07:12

Gaz Winter