.NET Inside Out Part 25 – Using is broken revisited

This is the twentieth fifth part of the .NET Inside Out series. For your convenience you can find other parts in the table of contents in Part 1 – Virtual and non-virtual calls in C#

Some time ago we saw how the using construct is broken in C#. I provided some hacks around that but we can take a completely different approach thanks to the “new” C# syntax. Let’s use exception filters to do so:

See this code

We use the same code with aborting the thread as the last time. However, we do not catch any exceptions, we let them pass but we keep track of them via exception filters. Notice how first filter just stores the exception, and the second filter modifies the exception in place. We could obviously throw aggregated exception instead but then we would need to do it in the catch block. Keep in mind this is not necessarily safe as reflection may throw another exception. Also, regular considerations regarding access violations apply.

Output:

Similar approach could be based on the app domain’s first chance exception event but identifying exceptions could be much harder in that case (as they may be handled deep inside the code or just thrown from completely other parts of the codebase).