Search code examples
c#debuggingconditional-compilation

Debug.Assert versus conditional compilation


Consider the code below:

#if DEBUG
    if (Systems.Contains(system))
        throw new InvalidOperationException("System already registered");
#endif

    Debug.Assert(!Systems.Contains(system), "System already registered");

Previously I used to do the former, I've since discovered Debug.Assert.

Is there a reason why I should not always prefer Debug.Assert?

  1. It only exists in debug code (it has the attribute [Conditional("DEBUG")]).
  2. It seems to me to be more suited to my intention (code sanity checks, rather than raising exceptions to be handled later).
  3. It's less code to write.

Solution

  • You can always use Debug.Assert(), because this class is complied with the DEBUG conditional as well:

    [Conditional("Debug")]
    

    Indicates to compilers that a method call or attribute should be ignored unless a specified conditional compilation symbol is defined.

    ConditionalAttribute is applied to the methods that are defined in the Debug and Trace classes.
    http://msdn.microsoft.com/en-us/library/system.diagnostics.conditionalattribute.aspx