Closing streamwriter

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
 
P

Peter Duniho

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
 

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