Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - How does ReSharper know "Expression is always true"?

Check out the following code:

private void Foo(object bar)
{
   Type type = bar.GetType();

    if (type != null) // Expression is always true
    {   
    }
}

ReSharper claims type will never be null. That's obvious to me because there's always going to be a type for bar, but how does ReSharper know that? How can it know that the result of a method will never be null?

Type is not a struct so it can't be that. And if the method were written by me, then the return value could certainly be null (not necessarily GetType, but something else).

Is ReSharper clever enough to know that, for only that particular method, the result will never be null? (Like there's a hard-coded list of known .NET methods which will never return null.)

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

JetBrains perfectly explains how ReSharper does this in their features list.

Summary from link (this particular question is about NotNullAttribute):

We have analyzed a great share of .NET Framework Class Library, as well as NUnit Framework, and annotated it through external XML files, using a set of custom attributes from the JetBrains.Annotations namespace, specifically:

StringFormatMethodAttribute (for methods that take format strings as parameters)
InvokerParameterNameAttribute (for methods with string literal arguments that should match one of caller parameters)
AssertionMethodAttribute (for assertion methods)
AssertionConditionAttribute (for condition parameters of assertion methods)
TerminatesProgramAttribute (for methods that terminate control flow)
CanBeNullAttribute (for values that can be null)
NotNullAttribute (for values that can not be null)
UsedImplicitlyAttribute (for entities that should not be marked as unused)
MeansImplicitUseAttribute (for extending semantics of any other attribute to mean that the corresponding entity should not be marked as unused)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...