.NET assert assertions included

How is asserted that assertions are included in C #?

Here's a link to a related answer for Java that doesn't work in C #.

The intent of this would be to prevent the use of release-type assemblies, because when efficiency is not a concern, I could work with all assertions, so a debug-type assembly is preferred in some places.

Usage Debug.Assert(false)

was unsatisfactory as it creates dialogue and requires user interaction. It would be nice to know that assertions work without "noise." Java solution is silent.

+3


source to share


1 answer


Update: There's a simpler solution out there. The rest is even lower for the curious.

public static bool AreAssertionsEnabled =
 #if DEBUG
  true
 #else
  false
 #endif
 ;

      

Looks disgusting, but pretty simple.


Let's first see what causes Debug.Assert

disappear in builds without DEBUG:



[Conditional("DEBUG"), __DynamicallyInvokable]
public static void Assert(bool condition)
{
    TraceInternal.Assert(condition);
}

      

This is [Conditional("DEBUG")]

. This inspires the following solution:

public static bool AreAssertionsEnabled = false;

static MyClassName() { MaybeSetEnabled(); /* call deleted in RELEASE builds */ }

[Conditional("DEBUG")]
static void MaybeSetEnabled()
{
    AreAssertionsEnabled = true;
}

      

Perhaps you can refactor this so that it AreAssertionsEnabled

could be readonly

. I just can't think of a way right now.

Now you can check the boolean AreAssertionsEnabled

and execute whatever logic you like based on.

+5


source







All Articles