0

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.

Alex Aparin
  • 4,393
  • 5
  • 25
  • 51
  • 4
    Possible duplicate of [#if DEBUG vs. Conditional("DEBUG")](http://stackoverflow.com/questions/3788605/if-debug-vs-conditionaldebug) – GSerg Nov 03 '16 at 09:27
  • According to MSDN: https://msdn.microsoft.com/en-us/library/aa664622(v=vs.71).aspx - there is no statement that body of method is included or not. The **call** for method is actually omited. – pwas Nov 03 '16 at 09:27

1 Answers1

5

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. The Conditional 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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194