R # alert tracking: possibly "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 when this can happen? (corner cabinets are good too)

 long[] ids = answers.Where(a => a.AnswerId.HasValue) .Select(a => a.AnswerId.Value) .ToArray(); 
+6
source share
3 answers

Since you are checking Where that a.AnswerId matters, a.AnswerId.Value will never throw an InvalidOperationException (unless another thread changes data at the same time). Resharper has good code analysis capabilities, but it cannot determine everything, in which case he does not understand that Where allows you to safely call .Value in Select , therefore, this is a warning. Therefore, you can safely ignore this warning.

+7
source

Unfortunately, ReSharper often encounters false positives. In this case, there will be no problem if AnswerId returns the same value when calling Where and Select . (Make sure AnswerId doesn't have some kind of crazy implementation that returns the number the first time it is accessed, and null second time.)

+4
source

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

+3
source

Source: https://habr.com/ru/post/906611/


All Articles