The sum of static properties is incorrect

My small class looks like this:

private static int field1 = - 1; private static int field2 = field1 + 1; public static void Sum() { field1 = 10; Debug.WriteLine(field2); } 

Calling Sum () writes '0'. Why?

+4
source share
4 answers

These are not properties - these are fields. field2 refers only to field1 during initialization - after that they are completely independent fields. This is not like the expression field1 + 1 revised each time field2 is read or field2 is written each time.

If you want field2 simply depend on the value of field1 , you should make this a property:

 // Note: I wouldn't actually call this Field2, of course... private static int Field2 { get { return field1 + 1; } } 
+12
source

This is because you are not updating prop2. You only initialize it at the beginning.

+2
source
 private static int prop1 = - 1; private static int prop2 = prop1 + 1; public static string Sum() { prop1 = 10; Debug.WriteLine(prop2); } 

This code never returns 1, The static property prop2 is initialized to zero. You are not performing an operation in the Sum () function. Thus, it simply returns an inilized value of zero "0"

0
source

you cannot control the initialization order of a static variable. If you really want this, you must do this in a static constructor:

 static class XYZ{ private static int field1; private static int field2; static XYZ { field1 = - 1; field2 = field1 + 1; } public static string Sum() { prop1 = 10; Debug.WriteLine(field2); } } 

As John said, I was mistaken in my assumption.

-1
source

All Articles