I have following program:
public class TestClass
{
[Conditional("DEBUG")]
static void debug_foo()
{
Console.WriteLine("DEBUG foo");
}
static int Main(System.String[] args)
{
debug_foo();
return 0;
}
}
I compiled program using Release mode. I found il code of debug_foo method in assembly. I cannot understand reason of such solution. I thought that if c# compiler can understand, that method is not used, then compiler need not to generate il code at all (for example, it will not generate call instruction in main function), beacuse it slows compilation and increase size of assembly.
The method logically still exists, and could be called by reflection, for example.
The C# 5 specification only talks about the calls being omitted - nothing about the implementation being omitted (section 17.4.2):
A method decorated with the
Conditional
attribute is a conditional method. TheConditional
attribute indicates a condition by testing a conditional compilation symbol. Calls to a conditional method are either included or omitted depending on whether this symbol is defined at the point of the call. If the symbol is defined, the call is included; otherwise, the call (including evaluation of the receiver and parameters of the call) is omitted.
Additionally, there are other situations (e.g. inheritance, or if the method were public) where it would still need to be present. Simply always keeping the method in IL is much simpler than expressing in the specification all situations in which it can be omitted.
See more on this question at Stackoverflow