I’m sure there are answers out there … but googling on “C# using” is a bit more complicated than you may expect.
At any rate … just really started learning about this handy technique the other day and it seems like I would be foolish to not use it for any non-primitive objects I have in my code.
Is that a fairly accurate statement or are there some downsides (outside of the slightly more cluttered code) to using “using” for almost everything?
As others have mentioned, you can only use a
usingstatement on types that implementIDisposable. For types that do implementIDisposable, the only real downside I have seen is due to the fact thatusingcalls the type’sDispose()method implicitly, so if an exception is thrown in that call, it is sometimes difficult to catch.Otherwise, I would recommend
usingfor types that implementIDisposableinstead of utilizing try-catch-finally as it makes code more compact and clean.Edit: found a good msdn article explaining this and other pitfalls.