Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch or flag potential problems due to the order of static field initialization

Consider the following C# code:

using System;
class Program
{
    static string string1 = "AAA";
    static string string2 = string1 + string3;
    static string string3 = "BBB";

    static void Main()
    {
        Console.WriteLine(string2);
    }
}

I wrote some code like this earlier today and was expecting string2 to contain the value AAABBB, but instead it just contained AAA. I did some reading on the order of initialization of static variables, but it seems preferable to me that some type of warning or error would have been generated during compilation.

Two questions:

  1. Why is such code allowed to compile successfully? (and if the answer is: "because that's how the C# spec is written", then why was it written that way? Are there reasons I'm missing why this doesn't preferably always just throw a compile-time error?)

  2. Is there any way to get a compile-time warning or some other kind of flag if I end up inadvertently writing this kind of code again in the future?

like image 577
RSW Avatar asked Aug 05 '13 20:08

RSW


1 Answers

For question 2:

Tools like ReSharper catch these things. There might be a setting inside of Visual Studio that you can turn on for more verbose compilation output.

enter image description here

Here's the code after the Reshaper cleanup that produces "AAABBB"

class Program
    {
        private const string String1 = "AAA";
        private const string String2 = String1 + String3;
        private const string String3 = "BBB";

        static void Main()
        {
            Console.WriteLine(String2);
            Console.ReadLine();

        }

    }

As a side note, I'd say since we usually read from top to bottom it seems logical for the initialization to happen the same way as described in 10.4.5.1 of the C# specification.

like image 80
Jon Raynor Avatar answered Oct 29 '22 01:10

Jon Raynor