Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ReSharper handle Debug.Assert(..) correctly?

I my code I'm using the System.Function method Debug.Assert(..) for verify the input parameter at the beginning of a method (see following example code snipped):

public class TestClass : IInterface
{
}

public class Verifier
  {
     public static void Verify(IInterface objectToVerify)
     {
        Debug.Assert((objectToVerify is TestClass), "Passed object must be type of TestClass");

        // ReSharper (Version 7.1.1) marks here "Expression is always false
        if (!(objectToVerify is TestClass))
        {
           return;
        }

        // do something ...
     }
  }

If I comment out the Debug.Assert statement the ReSharper warning disappears. In my opinion, ReSharper has to ignore this Debug.Assert statement, because also if the Debug.Assert statement is not fulfilled, the code beneath is executed (e.g. in Release-mode)

What is your opinion? Or is there a alternative implementation idea?

like image 623
rhe1980 Avatar asked Jan 31 '13 14:01

rhe1980


2 Answers

No, I think resharper is wrong and the reason is simple: Resharper says the code is unreachable when we know for a fact it isn't.

Release build will always execute that code and debug builds will hit it if you click Ignore in the dialog.

It doesn't matter if continuing after a assert is a bug or not, it's still not unreachable code.

like image 154
Isak Savo Avatar answered Sep 20 '22 15:09

Isak Savo


ReSharper is smart enough to know that Debug.Assert() will stop execution if objectToVerify is not a TestClass. Therefore, the expression in your if statement is indeed always false (otherwise the if statement wouldn't be reached in the first place).

You can work around the warning by writing something like:

public static void Verify(IInterface objectToVerify)
{
    if (!(objectToVerify is TestClass))
    {
        Debug.Assert(false, "Passed object must be type of TestClass");
        return;
    }

    // do something ...
}
like image 32
Frédéric Hamidi Avatar answered Sep 18 '22 15:09

Frédéric Hamidi