If you want to know how to use it creatively in your own projects, check out some of your own codes for situations where a specific bit of code must be executed before exiting the closing block. These are situations where try / finally or using can help you.
In particular, if you tried to achieve this by catching all the exceptions, you really should change instead of try / finally or using .
If a template occurs multiple times, you can create a class that implements IDisposable to capture the template and allow you to call the template using the using statement. But if you have a specific case that seems one-time, just use try / finally .
Both are very similar, in fact - using is defined in terms of try / finally , but even if we had only using , we could build try / finally ourselves:
public class DisposeAnything : IDisposable { public Action Disposer; public void Dispose() { Disposer(); } }
Now you can say:
using (new DisposeAnything { Disposer = () => File.Delete(tempFileName) }) { // blah }
This is the same as:
try { // blah } finally { File.Delete(tempFileName); }
Just think of it as a way to get the code to execute when leaving the scope.
Daniel Earwicker
source share