Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

250
Views
C# 7 Pattern Matching

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?

about 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You cannot declare ve variable twice in same scope. But you can rewrite exception filter so that variable for ValueException<int> will be declared only once:

catch(Exception e) 
  when (((e as AggregateException)?.InnerException ?? e) is ValueException<int> ve)
{
   // ...
}

It's your one-liner to catch exception if it either was thrown directly or if it is wrapped into AggregateException.

Keep in mind that purpose of AggregateException is consolidating multiple exceptions into one exception object. There could be several inner exceptions, and some of them can be aggregate exceptions as well. So you should flatten aggregate exception and check all of its inner exceptions.


You can put 'unwrapping' part into extension method to improve readability of your code.

about 4 years ago · Santiago Trujillo Report

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!