Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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#

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
446 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...