Is ReSharper Debug.Assert (..) working correctly?

I have my code. I use the System.Function Debug.Assert(..) method to check the input parameter at the beginning of the method (see the following code fragment):

 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 on the Debug.Assert , the ReSharper warning will disappear. In my opinion, ReSharper should ignore this Debug.Assert , because also, if the Debug.Assert statement Debug.Assert not executed, the code below is executed (for example, in Release mode)

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

+4
source share
5 answers

ReSharper is smart enough to know that Debug.Assert() will stop execution if objectToVerify not TestClass . Therefore, the expression in your if indeed always false (otherwise, the if would not have been reached in the first place).

You can get 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 ... } 
+2
source

No, I think resharper is wrong, and the reason is simple: Resharper says that code is unreachable when we know that it is not.

A release build will always execute this code and debug builds if you click Ignore in the dialog box.

It does not matter whether the assert continued after an error or not, this is not yet unreachable code.

+8
source

Old question, but I just ran into this problem and solved it (cosmetically) by switching HeuristicUnreachableCode:

 Debug.Assert(false, "type/fieldNum not processed"); // ReSharper disable HeuristicUnreachableCode return null; // ReSharper restore HeuristicUnreachableCode 
+1
source

I read a Debug.Assert as "this false expression can never happen." A reconfiguration warning is consistent with this use. He just believes in your statement. When the then part of your statement is executed, your program has an error.

But you use it to check parameters during debugging in the public API. I would not use for this statement. You should make an exception in this case and eliminate your if(...)return .

0
source

You can use Code Contracts .

The code looks like this:

  public class Verifier { public static void Verify(IInterface objectToVerify) { Contract.Requires<ArgumentException>((objectToVerify is TestClass), "Passed object must be type of TestClass"); // do something ... } } 

It works in debug and release mode. More here

0
source

All Articles