c# - When are the static constructors executed, before or after static fields? -
consider have
public class classa { public string propertyb { get; set; } }
and use this
public class classd { static readonly classa propertye = new classa(); static classd() { propertye.propertyb = "valuef"; } }
but rest of code didn't work expected. rewrote classd, , worked
public class classd { static readonly classa propertye = new classa { propertyb = "valuef" }; }
in way these 2 code samples different? expected had same behavior, don't.
according msdn:
if class contains static fields initializers, those initializers executed in textual order prior executing static constructor.
the difference between 2 classes how propertye
initialized. in first, sample, classd.propertye
assigned first, classa.propertyb
. in second sample, classa.propertyb
assigned first, classd.propertye
. could produce different results.
you might have issues circular dependencies among fields. msdn article states:
it possible construct circular dependencies allow static fields variable initializers observed in default value state.
using system; class { public static int x; static a() { x = b.y + 1; } } class b { public static int y = a.x + 1; static b() {} static void main() { console.writeline("x = {0}, y = {1}", a.x, b.y); } }
produces output
x = 1, y = 2
Comments
Post a Comment