Closing streamwriter

  • Thread starter Thread starter tshad
  • Start date Start date
T

tshad

I always see people closing a streamwriter as:

if (sw != null)
sw.Close().

But if you do an sw.Close() it doesn't set the value of sw to null.

I ran into an issue where I was writing to a streamwriter that was not open
and got an error as expected.

But how do you check if a streamwriter is open if you can't check for null?

Thanks,

Tom
 
I always see people closing a streamwriter as:

if (sw != null)
sw.Close().

But if you do an sw.Close() it doesn't set the value of sw to null.

I ran into an issue where I was writing to a streamwriter that was not
open
and got an error as expected.

But how do you check if a streamwriter is open if you can't check for
null?

StreamWriter doesn't provide that. You'd either have to just try and
catch a possible exception, or keep track of it yourself.

That said, if you have code that is attempting to use a StreamWriter
instance that might be closed, IMHO you have a design problem, not a
feature request.

Pete
 
Back
Top