static variables in C#

N

Natalia DeBow

Hi,

I have a quick question. I am using a static variable to hold an instance
of the StreamWriter:
private static StreamWriter sw = File.AppendText("C:\\Temp\\Test.txt");

I am curious to find out how static resources are being disposed in C#. The
problem that I am having is I am opening to a file, write a text message and
then close it. However, if I try to write to the same file again, I
generate an ObjectDisposed exception, since the file was closed and the
FileStream has been disposed. So, I was thinking to let the GC to release
allocated resources and not call on Close method explicitly. But since the
StreamWriter resource that I am using is static, would the GC dispose it?
What is the lifecycle of static variables? What part of the memory do
static variables/methods reside in?

Thanks,
Natalia
 
A

Ali Khawaja

Scoping rules for static variables are same as instance variables.
If you want to continue writing to your file, don't close it.
Open it in static constructor, and close it in the dispose of your
class. That way its accessible to everyone instance of your class.

I am pretty sure that GC would dispose it just like anything else
provided it meets the conditions for garbage collection.

Ali
 

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