Search code examples
c#debuggingresharperassert

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?


Solution

  • 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 ...
    }