How does ReSharper know this return type is never null?
I'm using ReSharp开发者_Go百科er 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?
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"
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.
精彩评论