How Does Resharper Know “Expression is always true”?

。_饼干妹妹 提交于 2019-12-29 01:33:09

问题


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)


回答1:


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)



回答2:


Yes, it basically has knowledge of some well-known methods. You should find the same for string concatenation too, for example:

string x = null;
string y = null;
string z = x + y;

if (z == null)
{
    // ReSharper should warn about this never executing
}

Now the same information is also becoming available via Code Contracts - I don't know whether JetBrains is hooking directly into this information, has its own database, or a mixture of the two.




回答3:


GetType is not virtual. Your assumption is most likely correct in your last statement.

Edit: to answer your comment question - it can't infer with your methods out of the box.




回答4:


object.GetType is not virtual, so you cannot yourself implement a version that returns a null value. Therefore, if bar is null, you will get a NullReferenceException and otherwise, type will never by null.



来源:https://stackoverflow.com/questions/5067819/how-does-resharper-know-expression-is-always-true

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!