I’m somewhat new to c#, more accustomed to scripting languages. I like the idea of ‘using’, you instantiate an object, and then you operate within its scope as long as you need it, then you let it dispose of itself when it’s done its purpose.
But, it’s not natural for me. When people show me examples using it, I recognize it as a good tool for the job, but it never occurs to me to solve problems with it in my own programming.
How can I recognize good places to use using and how do I use it in conjunction with try-catch blocks. Do they go inside the block, or do you usually want to enclose a using statement within a try block?
I rarely write try/catch blocks – most exceptions get thrown up to (near) the top of the stack. If I do need a try/catch block, I’m not sure I’m particularly consistent between putting it inside the
usingstatement vs outside. It really depends on whether you want the resource to be disposed before of after your exception handling code is run.If you’re asking about when you should be writing
usingstatements – any time you ‘own’ an object which implementsIDisposable(either directly or indirectly through inheritance) and control its lifetime. That’s usually an object which uses an unmanaged resource like a file handle or network connection. It’s not always hugely obvious, but you learn through experience. Almost anything to do with IO will be disposable, and Windows handles (for fonts etc) are similar.