This is ReSharper 7 with Visual Studio 2012. With the sample below
// This code works fine and as expected and ReShrper is happy with it
if (!string.IsNullOrWhiteSpace(extension) && extension.Length == 3)
{
// do something
}
// ReSharper highlights "extension" in extension.Length with "Possible 'System.NullReferenceException'"
if (!extension.IsNullOrWhiteSpace() && extension.Length == 3)
{
// do something
}
And, I have created the following extension method:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(this string s)
{
return string.IsNullOrWhiteSpace(s);
}
}
I looked at the reflected code of String.IsNullOrWhiteSpace and it doesn’t have any related code or attribute that would highlight to R# that the check is verified. Is this hardcoded in R#?
I looked at Code Contracts, but I am not sure it would help in my case.
Do you have a workaround for proving to ReSharper that the check condition is already verified by my extension method?
Available in Resharper 7 and above
Your project isn’t going to know what
ContractAnnotationis. You need to add it to your project. The preferred method is via nuget:Alternatively you can directly embed the source into your project:
Then paste that into a new file, eg Annotations.cs. The
ContractAnnotationdefinition lives in that file. For an official article on ContractAnnotation see herePrevious answer (for non R#7 versions)
No, Resharper uses External Annotations to provide this functionality. This article should answer all your questions, including a solution to provide your own external annotation for your
IsNullOrWhiteSpacemethod.Example
note: external annotations appear to only work on referenced libraries; if your reference is from a project the external annotations are not picked up; this is less than ideal
Suppose you have your extension method in a class called
TempExtensionswhich itself resides in an assembly namedClassLibrary1You need to add a new file at this location
The contents of the xml should contain: