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 }
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.
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!
Liz Parry - Owner - The Curious Cat - Cocktail Bar & Kitchen | LinkedIn.
Curious Cat app is a legit and safe mobile-only platform that will pay you for completing paid tasks.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With