Main Site Documentation

Static ctor ordering


#1

Me thinks there is an issue/bug with static ctor call order in general. A class with a static ctor that depends on a static ctor in another class causing some kind of circular issue. Before spending time making some simple code, is this a known issue already? tia


#2

No known issues.


#3

Add debug print to ctors and see what is happening


#4

Here is simple example showing the non-construction dependency issue.


    public class Static1
    {
        static string myVar;

        static Static1()
        {
            myVar = Static2.MyVar;
        }
        public static string MyVar
        {
            get { return myVar; }
        }
        public static void TestIssue()
        {
            string mv = Static1.MyVar;
            if (mv == null)
                Debug.Print("MyVar is null."); //OUTPUT is null running this test.
            else
                Debug.Print(mv);
        }
    }
    public class Static2
    {
        static string myVar;
        static Static2()
        {
            myVar = "Static2Value";
        }
        public static string MyVar
        {
            get { return myVar;}
        }
    }

If you require a value in ctor1 that constructed in ctor2 you get null, instead of the value. Same code works correctly in Big.Net. IIRC, ordering this correctly in .net was non-trivial. So maybe they took some shortcuts and missed the side effects. I am sure other more useful examples can be found.


#5

You are correct. It turns out to be something that is not supported by NETMF. We will open an issue for it.


#6

If anyone wants to keep track:

http://netmf.codeplex.com/workitem/980


#7

It is also possible “lock” this up on a single type. Don’t have the code as I had to work around it. So static ctor in general seems to have issues.


#8

From some basic experimentation, it appears that static constructors are executed within an application in .NETMF in alphabetical order and has nothing to do with dependencies whatsoever.