Actually, when you divide the material into several methods, a βgeneralβ connection (inside, for example, a class) can occur. For this, a closure-based pattern works very well:
public void Do() { WithConnection(o => { o.Foo(); o.Bar(); }); } private void WithConnection(Action<ThisClass> action) { try { con.Open(); action(this); } finally { con.Dispose() } }
I agree that in this special case, the union can be your friend, but if you want to have an available resource using several methods (follow several steps that usually trigger an event, but you only want one event, etc. etc. ), closing, as shown, may be your friend.
source share