473,326 Members | 2,192 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

Proper use of the "using" statement

Hi all,

I have a class SwitchCursor, that implements IDisposable. Is it legal
to use an object that is not assigned to a reference inside a using
statement like this:

using(new SwitchCursor())// is the SwitchCursor safe from GC?
{
}

or is the Object eligible for GC?

Thanks in advance,
Andy
Nov 15 '05 #1
10 1566
Andreas Müller <an***************@gmx.de> wrote:
I have a class SwitchCursor, that implements IDisposable. Is it legal
to use an object that is not assigned to a reference inside a using
statement like this:

using(new SwitchCursor())// is the SwitchCursor safe from GC?
{
}

or is the Object eligible for GC?


You can't do that, as the syntax for the using construct requires that
you assign the value to a variable.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #2
Jon,

Actually, you can do that. According to section 8.13 (The using
statement) of the C# spec, the using keyword only requires a valid
expression or a local variable declaration. I think that the C#
programmer's reference is incorrect.

The following code:

using (new System.Data.DataSet())
{
}

will compile. It also creates an implicit variable declaration which it
is stored in. This will keep it from being GCed until the using block
exits.

Hope this helps.

--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
Andreas Müller <an***************@gmx.de> wrote:
I have a class SwitchCursor, that implements IDisposable. Is it legal
to use an object that is not assigned to a reference inside a using
statement like this:

using(new SwitchCursor())// is the SwitchCursor safe from GC?
{
}

or is the Object eligible for GC?


You can't do that, as the syntax for the using construct requires that
you assign the value to a variable.

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #3
I believe it is safe for SwitchCursor to be used this way.

Tu-Thach
-----Original Message-----
Hi all,

I have a class SwitchCursor, that implements IDisposable. Is it legalto use an object that is not assigned to a reference inside a usingstatement like this:

using(new SwitchCursor())// is the SwitchCursor safe from GC?{
}

or is the Object eligible for GC?

Thanks in advance,
Andy
.

Nov 15 '05 #4
Nicholas Paldino [.NET/C# MVP] <mv*@spam.guard.caspershouse.com> wrote:
Actually, you can do that. According to section 8.13 (The using
statement) of the C# spec, the using keyword only requires a valid
expression or a local variable declaration. I think that the C#
programmer's reference is incorrect.

The following code:

using (new System.Data.DataSet())
{
}

will compile. It also creates an implicit variable declaration which it
is stored in. This will keep it from being GCed until the using block
exits.


Ah - I was misreading the ECMA spec. Doh :(

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #5
How would that be used? I mean if you can't access that dataset since you
don't know the implicit variable name what is the purpose of creating it?

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:eJ**************@TK2MSFTNGP09.phx.gbl...
Jon,

Actually, you can do that. According to section 8.13 (The using
statement) of the C# spec, the using keyword only requires a valid
expression or a local variable declaration. I think that the C#
programmer's reference is incorrect.

The following code:

using (new System.Data.DataSet())
{
}

will compile. It also creates an implicit variable declaration which it is stored in. This will keep it from being GCed until the using block
exits.

Hope this helps.

Nov 15 '05 #6
Daniel Billingsley <db**********@NO.durcon.SPAAMM.com> wrote:
How would that be used? I mean if you can't access that dataset since you
don't know the implicit variable name what is the purpose of creating it?


It could be used for locking purposes, or possibly tracing purposes.
For instance:

using (new TraceBlock ("doing something"))
{
...
}

where TraceBlock would have a static thread-local stack of "names" in
it, which could be dumped if you wanted. Creating a new TrackBlock
would add the name to the stack, and disposing it would pop the top
element.

That's just an example off the top of my head, and it's not terribly
good. I'm sure it's quite rare, but there are probably a few real cases
around :)

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 15 '05 #7
On Wed, 15 Oct 2003 12:43:18 +0100, Jon Skeet [C# MVP] <sk***@pobox.com>
wrote:
Daniel Billingsley <db**********@NO.durcon.SPAAMM.com> wrote:
How would that be used? I mean if you can't access that dataset since
you
don't know the implicit variable name what is the purpose of creating
it?


It could be used for locking purposes, or possibly tracing purposes.
For instance:


Another possible use might be with a product such as Raize CodeSite, in
which you could scope tracing. The constructor would then log the entry
into the scope, and the destructor/finalize method would log the exit out
of the scope. This could provide timing information as well as provide you
with a stack-trace like log for evidence gathering for a particularly
hard-to-find problem. Just a thought anyway.

(To Jon: Sorry about the email, I tried the "Quick Reply" of Opera and it
used email reply in a newsgroup)

--
Lasse Vågsæther Karlsen
http://www.vkarlsen.no/
PGP KeyID: 0x0270466B
Nov 15 '05 #8
[Please do not mail me a copy of your followup]

Jon Skeet [C# MVP] <sk***@pobox.com> spake the secret code
<MP************************@msnews.microsoft.com > thusly:
That's just an example off the top of my head, and it's not terribly
good. I'm sure it's quite rare, but there are probably a few real cases
around :)


There are lots of examples where anonymous items in a using statement
are useful. Basically, any time you have to do something like this:

try
{
StartSomething();
// do stuff
}
finally
{
EndSomething();
}

You can encapsulate the Start/End inside an IDisposable class. An
extremely simple example is a helper class that puts up a wait cursor
around a potentially long operation:

public class CursorWaiter : IDisposable
{
public CursorWaiter()
{
Cursor.Current = Cursors.WaitCursor;
}
~CursorWaiter()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
Cursor.Current = Cursors.Default;
}
}
}

// ...
using (new CursorWaiter())
{
// do slow stuff
}

You don't need a name for the CursorWaiter() instance because you
don't need to access it within the enclosed scope.
--
"The Direct3D Graphics Pipeline"-- code samples, sample chapter, FAQ:
<http://www.xmission.com/~legalize/book/>
Pilgrimage: Utah's annual demoparty
<http://pilgrimage.scene.org>
Nov 15 '05 #9
So, doing something like...

using (new CursorWaiter())
{
try
{}
catch
{}
}

right?

In this "extremely simple" example that doesn't really provide any
tremendous advantage over just changing the cursor in the try and finally
blocks, does it? I realize it could be more beneficial if that helper class
did more - I'm just trying to make sure I'm not missing something here.

"Rich" <le*************@mail.xmission.com> wrote in message
news:Oe**************@TK2MSFTNGP11.phx.gbl...
[Please do not mail me a copy of your followup]

Jon Skeet [C# MVP] <sk***@pobox.com> spake the secret code
<MP************************@msnews.microsoft.com > thusly:
That's just an example off the top of my head, and it's not terribly
good. I'm sure it's quite rare, but there are probably a few real cases
around :)


There are lots of examples where anonymous items in a using statement
are useful. Basically, any time you have to do something like this:

try
{
StartSomething();
// do stuff
}
finally
{
EndSomething();
}

You can encapsulate the Start/End inside an IDisposable class. An
extremely simple example is a helper class that puts up a wait cursor
around a potentially long operation:

public class CursorWaiter : IDisposable
{
public CursorWaiter()
{
Cursor.Current = Cursors.WaitCursor;
}
~CursorWaiter()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
}
protected void Dispose(bool disposing)
{
if (disposing)
{
GC.SuppressFinalize(this);
Cursor.Current = Cursors.Default;
}
}
}

// ...
using (new CursorWaiter())
{
// do slow stuff
}

You don't need a name for the CursorWaiter() instance because you
don't need to access it within the enclosed scope.
--
"The Direct3D Graphics Pipeline"-- code samples, sample chapter, FAQ:
<http://www.xmission.com/~legalize/book/>
Pilgrimage: Utah's annual demoparty
<http://pilgrimage.scene.org>

Nov 15 '05 #10
[Please do not mail me a copy of your followup]

"Daniel Billingsley" <db**********@NO.durcon.SPAAMM.com> spake the secret code
<Of**************@TK2MSFTNGP12.phx.gbl> thusly:
So, doing something like...

using (new CursorWaiter())
{
try
{}
catch
{}
}

right?
Nope. The whole point of putting it in the using clause is that the
cursor will be restored no matter how you exit the enclosed block: a
shortcut return statement, an exception, or normal execution flow
through the last statement.
In this "extremely simple" example that doesn't really provide any
tremendous advantage over just changing the cursor in the try and finally
blocks, does it?


Yes, it does. You don't have to write the try/finally blocks if you
use the using statement, assuming that the only reason you wrote
try/finally in the first place was to restore the cursor when you
exited the "slow processing" step.
--
"The Direct3D Graphics Pipeline"-- code samples, sample chapter, FAQ:
<http://www.xmission.com/~legalize/book/>
Pilgrimage: Utah's annual demoparty
<http://pilgrimage.scene.org>
Nov 15 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Peng Yu | last post by:
For example, at the beginning of the C++ program, I say "using namespace std;" However, in the middle of the program, I want to disable "using namespace std;". Do you know how to do that? ...
5
by: a | last post by:
Is there a performance hit if I have many "using" statements that are unnecessary? For example: using System.Collections; when nowhere in my code I'm using System.Collections namespace. I'm...
4
by: Philipp Sumi | last post by:
Hello all I have a thread that performs some simple I/O within a loop that runs on a separate thread. I used the using keyword to ensure the writer's disposal: using (writer) { while...
5
by: charliewest | last post by:
I've implemented the USING statement to ensure that my newly created sql connection closes when my method is finished using it. The USING statement is wrapped in try/catch error handling statement....
14
by: MuZZy | last post by:
Hi, Lately i've been (and still am) fixing some memory leaks problems in the project i just took over when i got this new job. Among the other issues i've noticed that for localy created objects...
12
by: Steve Pope | last post by:
Compiling the following works on my system: file main.cpp: #include <iostream> namespace space { int foo; }
25
by: samjnaa | last post by:
Please check for sanity and approve for posting at python-dev. In Visual Basic there is the keyword "with" which allows an object- name to be declared as governing the following statements. For...
3
by: Wolfgang Meister | last post by:
Is there a way to let VisualStudio insert automatically (after pressing e.g. F7) missing "Using" statements at the top ? Or is there a menu which suggests inserts for using directives ? How...
2
by: tim007 | last post by:
Hi all, I have a doubt regarding the "Using" statement if i write a code like this.... using (sqlDataReader) { do something ....
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.