Rob Levine
Rob Levine

Reputation: 41328

How does ReSharper know this return type is never null?

I'm using ReSharper 5.0, and am wondering how its code analysis function knows to higlight the following assemblies == null with the comment "Expression is always false".

var directory = new DirectoryInfo("somedir");
FileInfo[] assemblies = directory.GetFiles("*.dll");

if (assemblies == null <<--- this is highlighted with "Expression is always false"
    || assemblies.Length == 0)
{
  _log.Warn("No assemblies found");
}

I'd understand if the return type was a value-type, which it isn't. I'd also understand if there was some sort of code contract or metadata stating .GetFiles() will never return null. but I don't think there is.

So - how does it know this? Am I missing something obvious, or does ReSharper have some privileged knowledge, such as an internal list of metadata about framework methods? Or does it actually "introspect" the internal code and work it out?

Upvotes: 16

Views: 2202

Answers (2)

Hadi Hariri
Hadi Hariri

Reputation: 5016

As Tim points out, we annotate the .NET Framework. It's similar to what you get with Code Contracts, but done a little bit differently. If you look under the bin folder in ReSharper installation, you can see all the annotations.

Upvotes: 5

Tim Robinson
Tim Robinson

Reputation: 54764

The ReSharper developers ran flow analysis on the .NET framework binaries and determined which methods may or may not return null. Apparently DirectoryInfo.GetFiles never returns null.

You can annotate your own code to indicate the same set of rules, with a set of JetBrains. attributes. Take a look at the ReSharper site: http://www.jetbrains.com/resharper/features/code_analysis.html#Annotated_Framework

Edit: to answer your question specifically, "does ReSharper have some privileged knowledge, such as an internal list of metadata about framework methods" - yes, it came from "introspecting the internal code and working it out"

Upvotes: 25

Related Questions