Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

resharper

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();
like image 402
bevacqua Avatar asked Jan 23 '12 00:01

bevacqua


3 Answers

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.

like image 127
Thomas Levesque Avatar answered Nov 07 '22 23:11

Thomas Levesque


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.)

like image 4
Michael Liu Avatar answered Nov 07 '22 22:11

Michael Liu


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

like image 3
Evgeny Pasynkov Avatar answered Nov 07 '22 21:11

Evgeny Pasynkov