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?
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With