Alex Rivera | Logout

How does ReSharper know "Expression is always true"?

Asked 2011-02-21T15:31:06.007
15

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.)

Edit
Report

1 Answer

1

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.

answered 2011-02-21T15:33:56.973

Your Answer