2

I am looking for syntax that will test an expression and throw an exception if the result is false AND the DEBUG symbol is missing. But not when it is there.

I know I can use:

#if !DEBUG
  Trace.Assert(condition);
#endif

And I know I can use:

#if !DEBUG
  SomeGlobal.Production = true;
#endif

So I can write:

Trace.Assert(SomeGlobal.Production && condition);

to avoid having the compilation instructions in different places.

Any other way?

DavidRR
  • 18,291
  • 25
  • 109
  • 191
user1852503
  • 4,747
  • 2
  • 20
  • 28

2 Answers2

5
[Conditional("RELEASE")]
public static void AssertRelease(bool condition)
{
    Trace.Assert(condition);
}

And make sure to define "RELEASE" in Release configuration,


ConditionalAttribute is a good way to do this.

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

Just like Debug.Assert, calls to this method are left out by the compiler if the condition is not met.

Simon Farshid
  • 2,636
  • 1
  • 22
  • 31
3

Try this out:

#if !DEBUG
#define NOTDEBUG
#endif

namespace Test123
{
    using System;
    using System.Diagnostics;

    class Program
    {
        static void Main(string[] args)
        {
            var someCondition = false;

            Trace(someCondition);
        }

        [Conditional("NOTDEBUG")]
        static void Trace(bool condition)
        {
            if (!condition)
            {
                throw new Exception();
            }
        }
    }
}

See:

http://msdn.microsoft.com/en-gb/library/aa288458(v=vs.71).aspx

OzieGamma
  • 426
  • 3
  • 10