How does C# compiler remove Debug.Assert's in release builds?

前端 未结 3 511
栀梦
栀梦 2021-02-04 00:13

I was recently going through some code and considering whether I need to be careful with the expressions placed inside Debug.Assert statements, such as expensive op

3条回答
  •  被撕碎了的回忆
    2021-02-04 00:55

    I don't believe that Debug.Assert is special in any way; it's just using the Conditional attribute so that the compiler removes it when it detects that the 'preprocessor' define does not exist (C# does not have a preprocessor!).

    You can use it like so to do the same thing (so long as you've defined DEBUG (or whatever symbol you want to switch on, TRACE is another popular one):

    [Conditional("DEBUG"), Conditional("TRACE")]
    public void DebugOnlyMethod() {
        Console.WriteLine("Won't see me unless DEBUG or TRACE is defined");
    }
    

提交回复
热议问题