From ecc00608620fc7663eaf8d011280b631ddefdbd2 Mon Sep 17 00:00:00 2001 From: "gu.martinm@gmail.com" Date: Wed, 2 Jul 2014 13:00:43 +0200 Subject: [PATCH] Try-With-Resources C# (using statement thoughts) --- .../Try-With-Resources-C#/under_the_scenes.txt | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) 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) -- 2.1.4