-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Description
Currently Single throws an InvalidOperationException when no element was found, and throws an InvalidOperationException when more than one element was found. To tell them apart you'd have to look at the message text. I suggest creating two new exception classes and throwing a different one in the two cases. Since the new exceptions would inherit from InvalidOperationException, I believe this would be fully backward compatible.
Reproduction Steps
Something like this should work
int[] elems = { 1, 2, 3, 4 };
try { elems.Single(x => x % 2 == 0); }
catch (NoElementFoundException) { System.Console.WriteLine("none found"); }
catch (MultipleElementsFoundException) { System.Console.WriteLine("more than one found"); }
At the same time catch (InvalidOperationException) should continue to work as it does now.
Expected behavior
In the above example "more than one found" would be printed as that's the exception type thrown.
Actual behavior
(Currently these two exception types do not exist.)
Regression?
No
Known Workarounds
Currently you can inspect the message text of the exception, but this is messy and fragile.
Configuration
.NET 8
Other information
No response