From: gu.martinm@gmail.com Date: Wed, 2 Jul 2014 11:00:43 +0000 (+0200) Subject: Try-With-Resources C# (using statement thoughts) X-Git-Url: https://git.gumartinm.name/?a=commitdiff_plain;h=ecc00608620fc7663eaf8d011280b631ddefdbd2;p=CSharpForFun%2F.git Try-With-Resources C# (using statement thoughts) --- diff --git a/Allgemeines/Try-With-Resources-C#/Try-With-Resources-C#/under_the_scenes.txt b/Allgemeines/Try-With-Resources-C#/Try-With-Resources-C#/under_the_scenes.txt index 0b77632..57199f3 100644 --- a/Allgemeines/Try-With-Resources-C#/Try-With-Resources-C#/under_the_scenes.txt +++ b/Allgemeines/Try-With-Resources-C#/Try-With-Resources-C#/under_the_scenes.txt @@ -82,3 +82,33 @@ Program() } } +IMHO the best way to close resources is by means of the using statement. In this way you close always the resources even +if there are exceptions. Besides we do not have to write loads of code to achieve it. + + +The old way: + +MyResourceOne resourceOne; +MyResourceTwo resourceTwo; +try +{ + +} +finally +{ + if (resourceOne != null) + { + resourceOne.Dispose(); + } + + if (resourceTwo != null) + { + resourceTwo.Dispose(); + } +} + +The problem with this way is, if resourceOne.Dispose() throws exception I am not going to call resourceTwo.Dispose() :( + +BUT IF YOU WANT TO DO IT RIGHT (or at least as I think it is right) YOU MUST WRITE LOADS OF CODE, SO AT THE END IF YOU DO NOT USE +THE using statement THIS IS THE "BEST" SOLUTION (even if it is not perfect) BUT ALL DEPENDS ON YOUR CASE. With using statement you will +never have doubts :) SO ALWAYS USE THE using statement (AFAIU)