static variables in C#

  • Thread starter Thread starter Natalia DeBow
  • Start date Start date
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
 
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
 
Back
Top