Suppose I have the following exception filter
try {
...
} catch (Exception e) when (e is AggregateException ae && ae.InnerException is ValueException<int> ve || e is ValueException<int> ve) {
...
}
I could have simply written two separate catch
blocks, but I wanted to see how one could use the pattern matching feature to catch an exception that either is itself or is wrapped within an AggregateException
. Here, however, the compiler complains of a redefinition of ve
, which is understandable. I have seen a case where a pattern matched variable is reused within the same expression as shown here: https://blogs.msdn.microsoft.com/dotnet/2016/08/24/whats-new-in-csharp-7-0/
if (o is int i || (o is string s && int.TryParse(s, out i)) { /* use i */ }
so there is probably a way to do what I want. Or is there?
Not as nice as Sergey's solution, but you can also use different names and coalesque them:
try
{
...
} catch (Exception e)
when (e is ValueException<int> ve1 ||
e is AggregateException ae
&& ae.InnerException is ValueException<int> ve2)
{
var exept = ve1 ?? ve2;
// do something with exept
}
if you handle InnerExceptions of ValueException or general ValueException Exceptions the same.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With