using clause and implementing IDisposable

R

Razzie

Hi,

I know that as a general rule, whenever your class contains members that
implicitly or explicitly implement IDisposable, your class should too.
However, does it count when my class uses a using claus?

class A
{
private void doSomething()
{
using(StreamReader sr = new StreamReader(..))
{ // code }
}
}

1. Would class A still need to implement IDisposable, or is the using clause
completely 'safe'?
2. If I use a thy-catch clause around the using clause, and an exception
occurs, will some resources (the StreamReader) not get cleaned up properly?
(And maybe that would be the answer to number 1, eg. Yes I should still
implement IDisposable?)
3. When using the using clause, would I still need to call sr.Close()? I
take it the Close() method eventually calls the Dispose() method too, so it
wouldn't be necessary...

Thank you!

Razzie
 
J

Joerg Jooss

Razzie said:
Hi,

I know that as a general rule, whenever your class contains members
that implicitly or explicitly implement IDisposable, your class
should too. However, does it count when my class uses a using claus?

class A
{
private void doSomething()
{
using(StreamReader sr = new StreamReader(..))
{ // code }
}
}

1. Would class A still need to implement IDisposable, or is the using
clause completely 'safe'?

It's safe. No need to implement IDisposable in your class (it wouldn't help
anyway).
2. If I use a thy-catch clause around the using clause, and an
exception occurs, will some resources (the StreamReader) not get
cleaned up properly? (And maybe that would be the answer to number 1,
eg. Yes I should still implement IDisposable?)

"Using" is a syntactical shortcut for a try/finally block that invokes
Dispose() on the "used" IDisposable. Thus, it acts like a nested try block.
3. When using the using clause, would I still need to call
sr.Close()? I take it the Close() method eventually calls the
Dispose() method too, so it wouldn't be necessary...

Close() is (or should be) a synonym for Dispose() for types that support the
notion of closing, like readers, streams, or windows. In your example, "sr"
will be closed and thus also disposed.

Cheers,
 
B

Bonj

1. Would class A still need to implement IDisposable

No.

, or is the using clause
completely 'safe'?
Yes.

2. If I use a thy-catch clause around the using clause, and an exception
occurs, will some resources (the StreamReader) not get cleaned up
properly?

It will get cleaned up fine.
3. When using the using clause, would I still need to call sr.Close()? I
take it the Close() method eventually calls the Dispose() method too, so
it wouldn't be necessary...

As far as I know, Dispose() normally calls Close() as a matter of course.
 

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