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();
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.
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.)
Unfortunately, ReSharper cannot track condition checks through LINQ lambdas sequence. This is a known problem.
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