Are Debug.Assert / Debug.Fail automatically conditionally compiled #if "DEBUG"

Are Debug.Assert / Debug.Fail automatically conditionally compiled #if "DEBUG"? Or is it more like a lack of a debugger (even in a release), it just doesn't do anything? If so, are there any consequences for working with them in your code? Or are they really not intended for production code, only for test or conditional code?

+6
debugging c #
source share
3 answers

No, the whole call, including evaluating the expression, is removed from compilation if the character is not defined. This is very important - if there are any side effects in the expression, they will not occur if DEBUG is not defined. Here's a short but complete program to demonstrate:

using System; using System.Diagnostics; class Test { static void Main() { int i = 0; Debug.Assert(i++ < 10); Console.WriteLine(i); } } 

If DEBUG defined, it returns 1, otherwise it will print 0.

Because of this behavior, you cannot have an out parameter for a conditionally compiled method:

 using System; using System.Diagnostics; class Test { static void Main() { int i ; MethodWithOut(out x); } [Conditional("FOO")] static void MethodWithOut(out int x) { x = 10; } } 

This gives an error:

Test.cs (13,6): error CS0685: Conditional member 'Test.MethodWithOut (out int)' cannot have out parameter

+14
source share

The Debug.Assert / Fail API contains a ConditionalAttribute attribute with a value of "DEBUG", thus

 [Conditional("DEBUG")] public void Assert(bool condition) 

The C # and VB compiler will actually include a call to the is method if the DEBUG constant is defined when the method call is compiled in code. If it is not, the method call will be excluded from IL

+6
source share

Yes, to a large extent. Debug methods are decorated with the [Conditional ("DEBUG") attribute, so calls to Debug methods will not be compiled into IL if the DEBUG character is defined.

Learn more about ConditionalAttribute on MSDN.

+2
source share

All Articles