Making Reshaper recognize custom asserts

I have an "asserter" class with different assert methods.

If I have code like this:

  MyAsserter.Assert(x !== null);
  x.Foo();

Resharper complains that 'x' might be null on the second line.

Is there a way to make Resharper recognize my custom asserts? Is this a FAQ? (I couldn't find the answer)

4 comments
Comment actions Permalink

Hello,

Is there a way to make Resharper recognize my custom asserts? Is this
a FAQ? (I couldn't find the answer)


Have a look at the JetBrains.Annotations.AssertionMethodAttribute and JetBrains.Annotations.AssertionConditionAttribute
classes from ReSharper annotations.


Serge Baltic
JetBrains, Inc — http://www.jetbrains.com
“Develop with pleasure!”


0
Comment actions Permalink

Thanks Serge!

For some reason I couldn't get this to work (Resharper nigthly builds, including the beta).
I added the JetBrains.Annotations definitions to my solution (from options -> code annotations -> copy default implementation to clipboard), annotated my assert methods, but R# still warns me about possible nulls.

I sometimes even get this strange behavior (both with and without the annotations):

  foo.DoSomething(); // no warning

But if I add an assert:

  MyAssert.Assert(foo != null);
  foo.DoSomething(); // warning about possible null

I guess I'm doing something wrong, but I don't know what it is.

0
Comment actions Permalink

Hello,

Found a working example in our codebase. Does your assertion method declaration
look like this?

   
    public static void Assert(
bool condition, string message)

As for the case

  MyAssert.Assert(foo != null);
  foo.DoSomething(); // warning about possible null

it's pretty OK for the warning to appear -- provided that the Assert method
is not recognized as an assertion. This means you have optimistic analysis
turned on, and R# won't show warnings for variables not known to be possibly
null. But after you add a null-check, like this: "foo != null", R# sees that
foo is sometimes indeed expected to be null (why would you check otherwise),
hence the warnings on other usages. This does not apply to assertion method
conditions, of course.


Serge Baltic
JetBrains, Inc — http://www.jetbrains.com
“Develop with pleasure!”


0
Comment actions Permalink

Hi Serge,

No, I didn't mark the condition with [AssertionCondition], that must be it.
I wonder how I missed this was required.

Interesting to know about optimistic analysis.

Thanks for the help!

0

Please sign in to leave a comment.