Since the C# using
statement is just a syntactic sugar for try/finally{dispose}, why does it accept multiple objects only if they are of the same type?
I don't get it since all they need to be is IDisposable. If all of them implement IDisposable it should be fine, but it isn't.
Specifically I am used to writing
using (var cmd = new SqlCommand()) { using (cmd.Connection) { // Code } }
which I compact into:
using (var cmd = new SqlCommand()) using (cmd.Connection) { // Code }
And I would like to compact furthermore into:
using(var cmd = new SqlCommand(), var con = cmd.Connection) { // Code }
but I can't. I could probably, some would say, write:
using((var cmd = new SqlCommand()).Connection) { // Code }
since all I need to dispose is the connection and not the command but that's besides the point.
The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.
The using statement is used to set one or more than one resource. These resources are executed and the resource is released. The statement is also used with database operations. The main goal is to manage resources and release all the resources automatically.
The using keyword has two major uses: The using statement defines a scope at the end of which an object will be disposed. The using directive creates an alias for a namespace or imports types defined in other namespaces.
There's no with keyword in C#, like Visual Basic. So you end up writing code like this: this. StatusProgressBar.
There's no particularly good technical reason; we could have come up with a syntax that allowed multiple declarations of nonhomogeneous types. Given that we did not, and there already is a perfectly good, clear, understandable and fairly concise mechanism for declaring nested using blocks of different types, we're unlikely to add a new syntactic sugar just to save a few keystrokes.
You can do this though:
using (IDisposable cmd = new SqlCommand(), con = (cmd as SqlCommand).Connection) { var command = (cmd as SqlCommand); var connection = (con as SqlConnection); //code }
Perhaps that would be satisfactory to you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With