bevacqua
bevacqua

Reputation: 48546

follow up on R# warning: Possible 'System.InvalidOperationException'

I have the following expression, where a.AnswerId is of type long?. ReSharper warns of a possible InvalidOperationException in the select function. Is there ever a case where this could actually happen? (corner-cases are fine too)

long[] ids = answers.Where(a => a.AnswerId.HasValue)
                    .Select(a => a.AnswerId.Value)
                    .ToArray();

Upvotes: 6

Views: 2278

Answers (3)

Evgeny Pasynkov
Evgeny Pasynkov

Reputation: 693

Unfortunately, ReSharper cannot track condition checks through LINQ lambdas sequence. This is a known problem.

Upvotes: 3

Michael Liu
Michael Liu

Reputation: 55499

Unfortunately, ReSharper often comes up with false positives. In this case, there won’t be a problem as long as AnswerId returns the same value in the calls to Where and Select. (Make sure AnswerId doesn’t have some crazy implementation that returns a number the first time you access it and null the second time.)

Upvotes: 4

Thomas Levesque
Thomas Levesque

Reputation: 292615

Since you check in the Where that a.AnswerId has a value, a.AnswerId.Value will never throw an InvalidOperationException (unless another thread is changing the data at the same time). Resharper has pretty good code analysis capabilities, but it can't spot everything, and in this case it doesn't realize that the Where makes it safe to call .Value in the Select, hence the warning. So you can safely ignore this warning.

Upvotes: 8

Related Questions