DEV Community


C# Using Statements

Joe Enos
Software developer/architect, mostly working with .NET and SQL Server.
・1 min read

Recently C# added "using" statements that can replace "using" blocks in many scenarios. It lets you auto-dispose of a disposable object at the end of the current block, rather than defining a brand new block.

This reduces the number of nested blocks your code needs. It's not unusual to have two nested using blocks, and that pushes your code way over. Now, you just need to structure your code so that it disposes at the end of the block (method, if/else block, old-fashioned using block, even a custom block).

Discussion (2)

patricktingen profile image
Patrick Tingen

If you use the using statement in a method in such a way that the variable is disposed at the end of the method, is there any advantage in using "using" instead of a normal variable definition?

jtenos profile image
Joe Enos Author

If it's disposable (implementing IDisposable), you want to make sure you dispose of it somehow - either in a using block, at the end of a block following the using statement, or directly by calling .Dispose() - ensuring that Dispose() will always fire even on exception (generally with try/finally). Functionally they're all the same, but skipping the disposal is definitely bad - could lead to connections not being closed, file handles remaining open, whatever the class does.