H2ONaCl
H2ONaCl

Reputation: 11269

.NET assert assertions are enabled

How does one assert that assertions are enabled in C#?

Here's a link to a related answer for Java, that does not work in C#.

The purpose of this would be to prevent the use of release-type assemblies because where efficiency is of no concern I might as well be running with all the assertions working, so there is in some places a preference for debug-type assemblies.

Use of Debug.Assert(false) was not satisfactory because it creates a dialog and requires user interaction. It would be good to know assertions work without the "noise". The Java solution is noiseless.

EDIT: This is taken from a comment under the accepted answer.

public static class CompileTimeInformation
{
    public static void AssertAssertionsEnabled()
    {
        // Recall that assertions work only in the debug version of an assembly.
        // Thus the assertion that assertions work relies upon detecting that the assembly was compiled as a debug version.

        if (IsReleaseTypeAssembly())
            throw new ApplicationException("Assertions are not enabled.");
    }

    public static bool IsReleaseTypeAssembly()
    {
        return ! IsDebugTypeAssembly();
    }

    public static bool IsDebugTypeAssembly()
    {
        return
            #if DEBUG
                true
            #else
                false
            #endif
        ;
    }
}

Upvotes: 3

Views: 468

Answers (1)

usr
usr

Reputation: 171188

Update: There's a simpler solution. The other one is still below for the curious.

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

Looks nasty but is quite simple.


Let's first look at what causes Debug.Assert to disappear in non-DEBUG builds:

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

It's [Conditional("DEBUG")]. That inspires the following solution:

public static bool AreAssertionsEnabled = false;

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

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

You can probably refactor this so that AreAssertionsEnabled can be readonly. I just can't think of a way right now.

You can now check the boolean value AreAssertionsEnabled and perform any logic you like based on it.

Upvotes: 6

Related Questions