Reputation: 321
I have written the below code but resharper is throwing
Possible 'System.InvalidOperationException'
What could be the reason?
Assert.Null(actual.Items?.FirstOrDefault(x => x.Date.Value.Year == 2019).Growth);
Upvotes: 0
Views: 217
Reputation: 23268
FirstOrDefault
call may return null
and you'll get an exception when accessing Growth
property, try to use null conditional operator ?.
one more time, like FirstOrDefault(x => x.Date.Value.Year == 2019)?.Growth
. It allows to avoid a NullReferenceException
As for InvalidOperationException
, x.Date
seems to have a Nullable<DateTime>
type, you should use HasValue
property before getting a Value
, like x => x.Date.HasValue && x.Date.Value.Year == 2019
. Or GetValueOrDefault()
method x => x.Date.GetValueOrDefault().Year == 2019
. Or even simper ?.
operator again x => x.Date?.Year == 2019
Upvotes: 1
Reputation: 66
I guess you should check for the
actual.Items?.FirstOrDefault(x => x.Date.Value.Year == 2019) to be null first and then go for take it in variable as
var currentItem = actual.Items?.FirstOrDefault(x => x.Date.Value.Year == 2019);
Assert.Null(currentItem .Growth);
Upvotes: 0