What would you prefer to see?
try
{
var item = list.Single(x => x.HasFoo);
}
catch(InvalidOperationException e)
{
throw new InvalidOperationException("Exactly one item with foo expected, none found", e);
}
Or:
var item = list.SingleOrDefault(x => x.HasFoo);
if (item == null)
throw new InvalidOperationException("Exactly one item with foo expected, none found");
What’s the best practice here? Which one makes the exception more comprehensible?
SingleOrDefault()if 0 or 1 items are expectedSingle()if 1, not 0 or 2 and more, item is expectedAlso keep in mind that there are a number of possible scenarios:
And:
And don’t forget about
First(),FirstOrDefault()andAny()