C# · CodeProject · Dotnet

Multiple Objects in Using block [TIP]

Dear Reader,

Today i saw Seans post and i must say its really good tip he has come out with. Infact i did not know until now. So i started to dig in more on this topic and wanted to see inside what IL does exactly and how things work.

So i used the below code:

So the output of this code prints Disposing string 3 times because we know that Using{} block calls Dispose method by default.

So i was curious as what the IL will be laid out by the compiler, since i already know that Using{} block on one object inside it, it will transform to try-finally{} block. But since i have declared 3 objects inside it, does it call 3 times dispose on those objects in 1 finally{} block or does it goes for a different approach.

Alas, upon seeing the IL, the compiler will just enclose multiple try-finally{} blocks for each of those objects inside the Using{} block and 3 Dispose calls in each finally block as shown:

Thats all dear friend, thanks to Sean for this TIP.

Thanks 🙂

P.S: Your comments/votes are much appreciated.

 

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s