Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using various types in a 'using' statement (C#)

Tags:

c#

types

using

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.

like image 484
Andrei Rînea Avatar asked Jun 08 '09 17:06

Andrei Rînea


People also ask

What is using () in C#?

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.

What is the use of using statement in C# with example?

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.

What are the different usages of the using keyword?

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.

Is there a with statement in C#?

There's no with keyword in C#, like Visual Basic. So you end up writing code like this: this. StatusProgressBar.


2 Answers

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.

like image 37
Eric Lippert Avatar answered Sep 20 '22 15:09

Eric Lippert


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.

like image 104
Joseph Avatar answered Sep 20 '22 15:09

Joseph