Recently I had the situation, that I wanted to write something into a log file and in the same time the message should be displayed as a debug message as well.
I had a file log method looked like this:
string AddMessage(string message)
So I worte the following code:
Debug.WriteLine(AddMessage("message"))
Well, when I shipped the code to the productive environment, my message never got into the log file. So first, I checked if the newest code was installed. Version number seemed to be Ok. Strange.
Then I made some considerations:
- The code for productive environment was compiled in release mode: Should not affect my code - I haven't a debug directive and if WriteLine(...) has one, so what.
- In productive environment, there is no debugger: No problem for me, with release build I won't see debug messages anyway.
So I thought, probably I had not saved my code properly or the check-in failed or something like that and I built it again. Same result.
No I took a look into the shipped assembly with IL-Spy (a nice assembly reflection tool) and the whole code line for Debug.WriteLine(...) was missing. Only explanation: The compiler optimization stripped that line away and did not take consideration that AddMessage(...) still has the right to exist.
So I dissect AddMessage(...) from Debug.WriteLine(...) and all went fine. This article is just to remind you, that in circumstances you need to be aware of compiler optimization and that it not always works as you expect to do so.