开发者

How do I get rid of "Possible System.NullReferenceException" warnings when using LINQ and ReSharper?

Let's say I have the following code:

public class Deck {
  [NotNull IEnumerable<Card> cards = new List<Cards>();
  [NotNull] public IEnumerable<Card> Cards { get; private set; }

  public void AddCard([NotNull] Card card) { cards.Add(card); }
  ...
}

public static IEnumerable<int> CardValuesOfColor(this Deck deck, Color color)
{
  var cards = deck.Cards;
  return cards.Where(c => c.Color == color).Select(c => c.Value);
}

When running ReSharper Code Inspection, it rightly complains about a possible System.NullReferenceException at "deck.Cards", since deck could be null in this code. This is a good thing, I want to keep this.

However, it will also complain about c.Color and c.Value, as it feels c could be null in these cases. This seems excessive and less than helpful.

I can "fix" the c.Color by changing the lambda from "c.Color == color" to "c != null && c.Color == color", although this is a pain for every Where clause, especially when I know from the class design that deck.Cards will not hold nulls.

This does not fix the c.Value issue, even开发者_运维百科 though it is clear that after the modified "where" clause, c cannot possibly be null.

It seems there is no way to write a Select(...), OrderBy(...), etc clause without triggering this warning.

When I turn on looking for possible null references in my project, I get hundreds of files with "problems". We use LINQ extensively, and so many, but not all, of these "problems" are spurious but impossible to turn off.

My choices appear to be to turn off the possible null reference check or to annotate every single use of LINQ's Select() extension with a comment. Neither of which really work for me.

Is there a third choice that will solve this problem?


You have to keep in mind that ReSharper is a static code analysis tool, ie, it looks at patterns in your code without taking the context of that code into consideration and then suggests 'improvements' or 'fixes' based on what somebody at ReSharper (or yourself if you customized the settings) deem to be 'better'.

The problem with static analysis is that it has no concept about the intent of your code and therefore you are guaranteed that it will sometimes suggest 'improvements' that actually makes your code worse, because it lacks the context of what is appropriate for the meaning that your code is trying to express.

This is the same argument as "for every rule there is an exception" and people that use tools like ReSharper (like myself) should not blindly follow these suggestions.

On a related note: Code contracts will help you fix the problem

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜