Reputation: 48546
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
Reputation: 693
Unfortunately, ReSharper cannot track condition checks through LINQ lambdas sequence. This is a known problem.
Upvotes: 3
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
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