using clause and implementing IDisposable

  • Thread starter Thread starter Razzie
  • Start date Start date
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
 
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,
 
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.
 
Back
Top