Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to make Resharper treat Trace.Assert like Debug.Assert?

Tags:

c#

resharper

It understands that if the assertion is false that Debug.Assert will throw rather than continue and thus it knows the assertion is true past that point.

I'd like the same reasoning for Trace.Assert. Yeah, you can continue, if you continue past such a warning and it then throws on a null that's your problem. I want to get rid of those spurious possible null reference messages.

like image 552
Loren Pechtel Avatar asked Aug 24 '15 20:08

Loren Pechtel


People also ask

What is Debug Assertion?

Typically, the Assert(Boolean) method is used to identify logic errors during program development. Assert evaluates the condition. If the result is false , it sends a failure message to the Listeners collection.

What is trace Assert?

Checks for a condition; if the condition is false , outputs a specified message and displays a message box that shows the call stack. Assert(Boolean, String, String) Checks for a condition; if the condition is false , outputs two specified messages and displays a message box that shows the call stack.

Does Debug assert work in Release mode?

Assert() statements (as well as other Debug class method invocations) are ignored in a Release build.


1 Answers

I just tested this in ReSharper 9.1.3 with the following sample code.

private void M(string a)
{
    Trace.Assert(a != null); // or Debug.Assert(a != null);

    if (a == null)
        Console.WriteLine("a is null");
}

R# reported for both Debug.Assert() and Trace.Assert() that the Console.WriteLine() call is "heuristically unreachable". This is the case because both methods are annotated in ReSharper's external annotations with [ContractAnnotation("condition:false=>halt")] (you can see this by hitting Ctrl+Shift+F1 on the method and clicking on "[...]").

Which version of ReSharper/of the external annotations package do you have?

BTW: The condition:false=>halt annotation is not really correct because a) you could click "Ignore" in the DefaultTraceListener message box and execution will continue and b) it depends on the Trace.Listeners configuration (e.g. if you call Trace.Listeners.Clear() or set the AssertUiEnabled property to false the message box will not even appear).

like image 145
ulrichb Avatar answered Oct 20 '22 01:10

ulrichb