freeing resources

B

billq

Hello,
I am new to c# and have become confused about freeing resources. I need to
know if using an objects Dispose method does the same thing as setting the
object to null?

Pen bluePen = new Pen( Color.Blue, 2 );
//use pen
bluePen.Dispose();

as opposed to:

Pen bluePen = new Pen(Color.Blue, 2);
//use pen
bluePen = null;

I appreciate your help
thank you
bill
 
J

Jianwei Sun

No, it's different.

1> Call dispose will explicitly release the resources and the resource
will be freed immediately.

2> Set it to null will rely on the garbage collection to free it up.

The 1> is the recommended way to free the resource.
 
K

Kevin Spencer

This (the using statment) is an important point. If you use a class that
needs disposing, and it is not disposed, it can cause some serious problems,
depending on the class being used. A file that is opened, for example, will
cause the file to remain locked, until the app exits. So, it is important to
ensure that Disposable objects are Disposed. This *can* be done using
try/catch/finally, as in:

try
{
Pen bluePen = new Pen( Color.Blue, 2 );
//use pen
}
finally
{
if (bluePen != null) bluePen.Dispose();
}

However, if you use a using statement, it is much simpler:

using (Pen bluePen = new Pen(Color.Blue, 2)
{
//use pen
}

The using statement automatically disposes the object created when it passes
out of scope.

--
HTH,

Kevin Spencer
Microsoft MVP
Professional Chicken Salad Alchemist

What You Seek Is What You Get.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top