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

前端 未结 3 507
栀梦
栀梦 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:54

    Debug.Assert is declared with ConditionalAttribute; as the documentation states, this "[i]ndicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined."

    The C# compiler has specific support for that attribute and removes the Debug.Assert during release builds, so it is never part of the built expression tree.

    If you right-click on one of your Debug.Assert statements, you should be able to go to the definition. Visual Studio will show you "code" generated from the metadata, and there you can see the [Conditional("DEBUG")] attribute applied. So this code is only respected when DEBUG is #define'd as part of your build.

提交回复
热议问题