Say I have some statements like:
List<string> list = new List<string> {"1", "1", "2", "3", "4"};
try
{
Class1 c = new Class1
{
s1 = list.Single(s => s == "1"),
s2 = list.Single(s => s == "2"),
s3 = list.Single(s => s == "3"),
s4 = list.Single(s => s == "4")
};
}
catch (InvalidOperationException ex)
{
Console.WriteLine(ex.Message);
}
And I definitely will go to the catch block with an error “The input sequence contains more than one element” at this line:
s1 = list.Single(s => s == "1")
So, I just curious, it there any way to display error predicate in catch block? This will be very useful to fix the bugs, if we’ll see something like “There was a duplicate element “1” in sequence.” or even full predicate in string format. Can I somehow view this information and display or log it?
If you really need info about predicate and it’s parameters, then you can create your own
Singleextension method (it will be called instead of default method), which will actually wrap defaultSinglecall, but it will receiveExpression(expression tree that represents the lambda expression) instead ofFunc(lambda expression):On line
s1 = list.Single(s => s == "1")it will throw an exception and write pretty error message:Error on predicate s => s == "1"