if possible, I try to keep nesting of blocks to a minimum. In C#, there’s actually a good way of reducing nesting when combining using with the try catch finally within it.

So let’s see if we can try to reduce our ugly nesting further.

So, you want to use disposable resources, say some streams, and you want to do a try catch finally with those resources - you end up writing something like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using (var someResource1 = new MemoryStream())
using (var someResource2 = new MemoryStream())
{
    try
    {
        // do stuff
    }
    catch (Exception e)
    {
    }
    finally
    {
        // clean up
    }
}

So you’ve nested try catch finally in your using block - but there’s actually a cleaner way of doing the same thing. Check here:

1
2
3
4
5
6
7
8
9
10
11
12
13
using (var someResource1 = new MemoryStream())
using (var someResource2 = new MemoryStream())
try
{
    // do stuff
}
catch (Exception e)
{
}
finally
{
    // clean up
}

This reads quite well as it shows the intent of trying some computations or operations using resources, and as a bonus, we’ve just reduced our horrible nesting.