Reputation: 5355
Here is a problem which I encountered today.
I have a statement in C#
EmPayRollData emPayRollData = payroll.EmPayRollDatas.First();
Both payroll and EmPayRollData are entities. i.e. payroll is the parent and EmPayRollData is the child.
Now I have a statement:
companyRow.CompanyName = (empowerPayRollData == null) ? string.Empty : empowerPayRollData.Name;
I get a resharper comment saying: "Expression is always false"
Upvotes: 1
Views: 2141
Reputation: 273581
Resharper probably knows that .First()
will result in non-null or an exception.
From that it can be inferred that the expression will always be false.
If you expect empty result-sets, use .FirstOrDefault()
Upvotes: 1
Reputation: 62057
That is because First()
will either return an object or throw an exception if it can't. Resharper knows that if you get to that line, then empowerPayRollData won't be null. You might consider using FirstOrDefault
in this case.
Upvotes: 5
Reputation: 72920
If payroll.EmPayRollDatas
may be empty, you should instead use:
payroll.EmPayRollDatas.FirstOrDefault()
which will return null in the case of an empty enumerable. First
would throw an exception in this case, so if the line of code you are questioning were reached, the sequence is therefore not empty and your variable cannot be null.
Upvotes: 5