Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell Resharper that my IEnumerable method removes nulls?

Given the following code, Resharper will correctly warn me about a possible NullReferenceException on foo.Bar because there could be null elements in the enumerable:

IEnumerable<Foo> foos = GetFoos();
var bars = foos.Select(foo => foo.Bar);

One way to satisfy the static analyzer is to explicitly exclude nulls:

IEnumerable<Foo> foos = GetFoos().Where(foo => foo != null);

I find myself typing .Where(x => x != null) a lot, so I wrapped it up in an extension method, and now I can do the following:

IEnumerable<Foo> foos = GetFoos().NotNull();

The problem is that Resharper doesn't know that NotNull() strips out nulls. Is there a way I can teach Resharper about this fact? In general, is there a way to tell Resharper that an IEnumerable-returning method will never have nulls in it (so that I can just annotate GetFoos() directly)?

I know I can use the NotNullAttribute to tell Resharper that the enumerable itself is not null, but I can't find one that speaks about the contents of the enumerable.

Edit: The extension method looks exactly as you'd expect:

[NotNull]
public static IEnumerable<T> NotNull<T>(this IEnumerable<T> enumerable)
{   
    return enumerable.Where(x => x != null);
}
like image 872
ean5533 Avatar asked Oct 24 '14 22:10

ean5533


2 Answers

You could use ItemNotNullAttribute which tells ReSharper that no items in a collection can ever be null.

like image 76
Leonardo Avatar answered Nov 19 '22 10:11

Leonardo


One way as you stated is to use [NotNull] attribute which instruct Resharper engine to stop checking for null reference error for that particular variable.

Or else if you don't want to use that attribute you can optionally use the comments

// ReSharper disable PossibleNullReferenceException
        var bars = foos.Select(foo => foo.Bar);
// ReSharper restore PossibleNullReferenceException

To make a point to this question, Resharper cannot traverse through statement's runtime computational values so it can make a judgement that it cannot be null.

like image 35
Nandha Kumar Avatar answered Nov 19 '22 10:11

Nandha Kumar