Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get resharper to know that my variable is not null after I have called an extension method on it?

Tags:

c#

resharper

I have an extension method:

public static bool Exists(this object toCheck)
{
   return toCheck != null;
}

if I use it and then do something like this:

if (duplicate.Exists())
    throw new Exception(duplicate);

then resharper warns me that there is a possible null reference exception.

I know this is not possible, but how can I tell resharper that this is ok?

like image 443
Sam Holder Avatar asked Jun 20 '17 16:06

Sam Holder


2 Answers

You can do it with contract annotations, but the way provided in another answer does not work for me (that is - still produces a warning). But this one works:

public static class Extensions {
    [ContractAnnotation("null => false; notnull => true")]
    public static bool Exists(this object toCheck) {
        return toCheck != null;
    }
}

To get ContractAnnotationAttribute - recommended way is to install JetBrains.Annotations nuget package. If you don't want to install package - go to Resharper > Options > Code Annotations and press "copy implementation to clipboard" button, then paste it anywhere in your project (ensure to not change namespace).

like image 164
Evk Avatar answered Oct 23 '22 17:10

Evk


You can use "Contract Annotation Syntax" to indicate to Resharper that a method does not return normally under some circumstances, e.g. when a parameter is null.

For your example you can do something like this:

[ContractAnnotation(toCheck:notnull => true]
public static bool Exists(this object toCheck)
{
   return toCheck != null;
}

Where the toCheck:null => true tells Resharper that if toCheck is not null, the method will return true.

[EDIT] Updated link to point to the most recent Resharper documentation.

like image 3
Matthew Watson Avatar answered Oct 23 '22 18:10

Matthew Watson