G
Guest
Does .NET provide any guarantees as to the order in which static fields are
initialized? E.g. Sample 1 below appears to work as expected because
_myObject is initialized before InitializeSomeType() is called. Sample 2
throws a NullReferenceException because _myObject is not yet initialized when
InitializeSomeType() is called.
It appears that static fields are initialized in the order they appear in
the source file, but is this guaranteed?
----- Sample 1 -----
public class MyClass
{
private static object _myObject = new object();
private static SomeType _mySomeType = InitializeSomeType();
private static InitializeSomeType()
{
lock(_myObject)
{
...
}
}
}
----- Sample 2 -----
public class MyClass
{
private static SomeType _mySomeType = InitializeSomeType();
private static object _myObject = new object();
private static InitializeSomeType()
{
lock(_myObject)
{
...
}
}
}
initialized? E.g. Sample 1 below appears to work as expected because
_myObject is initialized before InitializeSomeType() is called. Sample 2
throws a NullReferenceException because _myObject is not yet initialized when
InitializeSomeType() is called.
It appears that static fields are initialized in the order they appear in
the source file, but is this guaranteed?
----- Sample 1 -----
public class MyClass
{
private static object _myObject = new object();
private static SomeType _mySomeType = InitializeSomeType();
private static InitializeSomeType()
{
lock(_myObject)
{
...
}
}
}
----- Sample 2 -----
public class MyClass
{
private static SomeType _mySomeType = InitializeSomeType();
private static object _myObject = new object();
private static InitializeSomeType()
{
lock(_myObject)
{
...
}
}
}