Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Curious C# using statement expansion

I've run ildasm to find that this:

    using(Simple simp = new Simple())     {         Console.WriteLine("here");     } 

generates IL code that is equivalent to this:

    Simple simp = new Simple();     try     {         Console.WriteLine("here");     }     finally     {         if(simp != null)         {             simp.Dispose();         }     } 

and the question is why the hell does it check null in the finally? The finally block will only be executed if the try block is executed, and the try block will only be executed if the Simple constructor succeeds (I.e. does not throw an exception), in which case simp will be non-null. (If there is some fear that some intervening steps might come between the Simple constructor and the beginning of the try block, then that would really be a problem because then an exception might be thrown that would prevent the finally block from executing at all.) So, why the hell?

Putting aside (please) the argument of whether the using statement is better than try-finally, I write my try-finally blocks as:

    Simple simp = new Simple();     try     {         Console.WriteLine("here");     }     finally     {         simp.Dispose();         simp = null;        // sanity-check in case I touch simp again                             // because I don't rely on all classes                             // necessarily throwing                             // ObjectDisposedException     } 
like image 964
Matthew Avatar asked Jun 03 '09 20:06

Matthew


People also ask

What is Curious Cat live?

Curious Cat is a free, small-scale social networking tool that allows you to connect with your followers by providing them with the appropriate tools to communicate with you, and you back to them, either anonymously or publicly. It is a question and answer system that allows people to ask you questions.

What is curious cat app?

CuriousCat is an anonymous Q&A social network, boasting millions of users world wide. It allows you to connect with your friends and followers uniquely thanks to anonymous questions and answers, so you can ask that burning question without feeling ashamed, and even answer some of your own!

Who owns Curious Cat?

Liz Parry - Owner - The Curious Cat - Cocktail Bar & Kitchen | LinkedIn.

Is it safe to use Curious Cat?

Curious Cat app is a legit and safe mobile-only platform that will pay you for completing paid tasks.


1 Answers

No, the finally block will ALWAYS be executed. You may not be getting the object from a new but from some other function that returns your object - and it might return NULL. using() is your friend!

dss539 was kind enough to suggest I include his note:

using(Simple simp = null)  

is yet another reason that the expansion must check for null first.

like image 116
n8wrl Avatar answered Oct 12 '22 23:10

n8wrl