In C#, using
statement is used to dispose in a deterministic manner the resources without waiting for garbage collector. For example, it may be used to:
Dispose SQL commands or connections,
Close streams, freeing the underlying source like a file,
Free GDI+ elements,
etc.
I noticed that using
is used more and more in cases where there is nothing to dispose, but where it's just more convenient for the caller to write a using
block rather than two separate commands.
Examples:
MiniProfiler, written by Stack Overflow team, uses
using
to denote blocks to profile:using (profiler.Step("Name goes here")) { this.DoSomethingUseful(i - 1); }
One alternative approach would be to have two blocks:
var p = profiler.Start("Name goes here"); this.DoSomethingUseful(i - 1); profiler.Stop(p);
Another approach would be to use actions:
profiler.Step("Name goes here", () => this.DoSomethingUseful(i - 1));
ASP.NET MVC also picked
using
for forms:<% using (Html.BeginForm()) { %> <label for="firstName">Name:</label> <%= Html.TextBox("name")%> <input type="submit" value="Save" /> <% } %>
Is such usage appropriate? How to justify it, given that there are several drawbacks:
Beginners would be lost, since such usage doesn't correspond to the one which is explained in books and language specification,
The code should be expressive. Here, the expressiveness suffers, since the appropriate usage of
using
is to show that behind, there is a resource, like a stream, a network connection or a database which should be released without waiting the garbage collector.
using
: The latter statement (e.g.profiler.Stop(p)
) is not guaranteed to be executed in the face of exceptions and control flow.