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);
}
You could use ItemNotNullAttribute
which tells ReSharper that no items in a collection can ever be null
.
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.
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