0
\$\begingroup\$

Should I check Count before Linq Single() call if I expect only one element?

if (objects.Count != 1)
{
    throw new
        InvalidOperationException(
            "%Collection% should contain one %element%, but now it's: "
                 + objects.Count);
        }

return objects.Single();

Single implements the same check and throwing. But its message is less specific.

P.S. in my case wrong count is handled just writing log message like

_log.Error("Error during %operation%", ex);
task.Complete(TaskResult.Fail);
\$\endgroup\$
  • \$\begingroup\$ For clarity, are you trying to alleviate the potential to avoid the error if Single grabs more than one element or executing on a null object? \$\endgroup\$ – Greg May 27 '16 at 14:11
  • \$\begingroup\$ @Greg I expects that collection should contain only one element. All other (0 or more than 1) is error. \$\endgroup\$ – SerG May 27 '16 at 14:56
  • \$\begingroup\$ @SerG Does the count matter? I could see an argument that you may want to log the contents of the collection when the error occurs, but I can't really see how the scalar count value helps much. \$\endgroup\$ – Dan Lyons May 27 '16 at 18:03
  • \$\begingroup\$ Yes, the count matters. You can't see because it's minimalized fragment. You can assume that items of collection are logged. \$\endgroup\$ – SerG May 31 '16 at 9:05
  • \$\begingroup\$ I almost always check the count myself because just like you've said, the message the Single methods outputs doesn't help at all. \$\endgroup\$ – t3chb0t Jun 16 '16 at 6:53
7
\$\begingroup\$

Yep, go for it. Adding more detail to error messages is helpful.

Also, depending on which style you prefer you could avoid explicitly checking the count by catching the exception thrown by Single().

try
{
    return objects.Single();
}
catch (InvalidOperationException ex) 
{
    throw new InvalidOperationException(
        "%Collection% should contain one %element%, but now it's: " + objects.Count,
        ex
    );
}
\$\endgroup\$
  • 1
    \$\begingroup\$ thats the better version +1 \$\endgroup\$ – Heslacher Jun 23 '16 at 10:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.