ReSharper: how to remove "Possible 'System.NullReferenceException'" warning
Asked Answered
A

6

12

Here is a piece of code:

IUser user = managerUser.GetUserById(UserId);
if ( user==null ) 
    throw new Exception(...);

Quote quote = new Quote(user.FullName, user.Email);

Everything is fine here. But if I replace "if" line with the following one:

ComponentException<MyUserManagerException>.FailIfTrue(user == null, "Can't find user with Id=" + UserId);

where function implementation is following:

public abstract class ComponentException<T> : ComponentException
        where T : ComponentException, new()
{
    public static void FailIfTrue(bool expression, string message)
    {
        if (expression)
        {
            T t = new T();
            t.SetErrorMessage(message);
            throw t;
        }
    }
    //...
}

Then ReSharper generates me a warning: Possible 'System.NullReferenceException' pointing on 1st usage of 'user' object.

Q1. Why it generates such exception? As far as I see if user==null then exception will be generated and execution will never reach the usage point.

Q2. How to remove that warning? Please note: 1. I don't want to suppress this warning with comments (I will have a lot of similar pieces and don't want to transform my source code in 'commented garbage); 2. I don't want to changes ReSharper settings to change this problem from warning to 'suggestion' of 'hint'.

Thanks.

Any thoughts are welcome!

P.S. I am using resharper 5.1, MVSV 2008, C#

Adversative answered 8/12, 2010 at 23:38 Comment(0)
F
6

Q1: Because Resharper doesn't do path analysing. It just sees a possible null reference and flags that.

Q2: You can't without doing either of what you provided already.

Foreconscious answered 8/12, 2010 at 23:45 Comment(0)
M
10

Resharper only looks at the current method for its analysis, and does not recursively analyse other methods you call.

You can however direct Resharper a bit and give it meta-information about certain methods. It knows for example about "Assert.IsNotNull(a)", and will take that information into account for the analysis. It is possible to make an external annotations file for Resharper and give it extra information about a certain library to make its analysis better. Maybe this might offer a way to solve your problem.

More information can be found here.

An example showing how it's used for the library Microsoft.Contracts can be found here.

Marlenmarlena answered 8/12, 2010 at 23:57 Comment(0)
P
9

A new answer in old post...

Here a little sample of my code regarding how to use CodeContract via ContractAnnotation with Resharper:

    [ContractAnnotation("value:null=>true")]
    public static bool IsNullOrEmpty(this string value)
    {
        return string.IsNullOrEmpty(value);
    }

It is very simple...if u find the breadcrumb in the wood. You can check other cases too.

Have a nice day

Precedent answered 26/3, 2014 at 15:28 Comment(1)
If you know that a method always throws an exception you can do [ContractAnnotation("=> halt")]Underpass
F
6

Q1: Because Resharper doesn't do path analysing. It just sees a possible null reference and flags that.

Q2: You can't without doing either of what you provided already.

Foreconscious answered 8/12, 2010 at 23:45 Comment(0)
S
3

You do know (or expect) that this code will throw an exception if there is a null reference:

ComponentException<MyUserManagerException>.FailIfTrue([...]);

However, since there is no contract specifying this, ReSharper has to assume that this is just a normal method call which may return without throwing any exception in any case.

Make this method implement the ReSharper contract, or as a simple workaround (which only affects debug mode, therefore no performance penalty for release mode), just after the FailIfTrue call:

Debug.Assert(user != null);

That will get rid of the warning, and as an added bonus do a runtime check in debug mode to ensure that the condition assumed by you after calling FailIfTrue is indeed met.

Scintillometer answered 9/12, 2010 at 0:34 Comment(2)
I wished it was true ... Resharper 5.1 fails to correctly identify Debug.Assert(user != null); and raises the warning. Is there any configuration I need to do?Asleep
Uh, R# 5.1 is pretty outdated, so I have nothing to test your issue on. Some hints however: Make sure that your code properly refers to the System.Diagnostics.Debug class as the code contract was defined for that, and not for arbitrary methods with that name/signature. Also, make sure that the build configuration is set to Debug (otherwise the code is out of scope and therefore the warning pops up!).Scintillometer
C
0

This is caused by the Resharper engine. These "possible NullReferenceException" happen because someone (probably at Resharper) has declared/configured somewhere an annotation on the method.

Here is how it works: ReSharper NullReferenceException Analysis and Its Contracts

Unfortunately, sometimes, these useful annotation are just wrong.

When you detect an error, you should report it to JetBrains and they will update the annotations on the next release. They're used to this.

Meanwhile, you can try to fix it by yourself. Read the article for more :)

Cosimo answered 8/12, 2010 at 23:53 Comment(0)
A
0

Please check if you have any user==null if check above the given code. If there is, then ReSharper thinks that the variable "can be null" so recommends you to use a check/assert before referencing it. In some cases, that's the only way ReSharper can guess whether a variable can or cannot be null.

Avant answered 15/10, 2018 at 8:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.