Dummy static initialization

Dummy static initialization

Old forum URL: forums.lhotka.net/forums/t/6391.aspx


emathias posted on Tuesday, February 10, 2009

Regarding the use of the _forceInit variable for proper static initialization...

Would the same initialization be forced by merely adding the line

private static int _forceInit = 1;

as opposed to coding a static constructor?

Thanks!

RockfordLhotka replied on Tuesday, February 10, 2009

No, because that static field won't be initialized until it is triggered - just like the static fields you are declaring for your property metadata.

The whole point here, is that .NET has specific rules about when static fields (like the one you show) are initialized, and it is often too late for what we need.

Static fields are initialized for a specific class (not subclass, not base class, just this class) when

a) a static field is accessed from that class

b) a static constructor is declared in that class, and any class member is accessed

Unfortunately, in Silverlight we ran into issues where (b) was not always correct, so only (a) appears totally reliable.

What you are showing is a field declaration - which is fine - but you still need some code to access that field to trigger the initialization. This must occur in two cases

a) when the object is created through a constructor

b) when the object is created through serialization (which doesn't invoke a constructor)

However, in CSLA .NET 3.6.1 I solved this problem and you don't need to worry about it any more (on .NET anyway). CSLA .NET now forcibly accesses at least one static field on each class in an inheritance hierarchy before allowing any property access, thus guaranteeing that the fields are initialized.

The same is true on Silverlight, but your static fields must be public in scope for it to work.

emathias replied on Tuesday, February 10, 2009

Then I've read some baaaaad info about static initialization. Wouldn't be the first time.

Thanks Rocky, and again for that 3.6.1 update.

RockfordLhotka replied on Tuesday, February 10, 2009

The only reliable info I have found is Brad Abram's blog post from months
ago. He spelled this out rather thoroughly, and the rules he lays out in
that post match my findings.

I suspect that most people have a set of assumptions about this (I sure did)
that aren't violated under normal circumstances, so we all assume the
assumptions are correct.

But as soon as you start to _rely_ on static field initialization,
especially in non-static methods, you quickly find out that those
assumptions are wrong...

This was my experience anyway :)

Rocky

Copyright (c) Marimer LLC