Cool Guy <co*****@abc.xyz> wrote:
Yes, that's guaranteed to only execute once. There are some caveats
about ordering when there's potential for a deadlock, but in simple
situations like the above (which 99% of static initializers fall into)
it's fine.
Could you give an example of one such caveat?
Sure. It's not actually a matter of initializing twice, but of the
incompletely initialized state being visible temporarily. For instance:
using System;
public class A
{
static string Something = B.Bar;
public static string Foo = "Hello";
}
public class B
{
public static string Bar = "There";
static B()
{
Console.WriteLine ("In B, A.Foo='{0}'", A.Foo);
}
}
public class Test
{
static void Main()
{
Console.WriteLine (A.Foo);
}
}
The results are:
In B, A.Foo=''
Hello
There are further rules for multithreaded system - I suggest you look
in the CLI spec, section 9.5.3.3 of partition 1 for further details.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too