Class Destructor Problem
Posted
by user279691
on Stack Overflow
See other posts from Stack Overflow
or by user279691
Published on 2010-03-27T12:19:48Z
Indexed on
2010/03/27
12:23 UTC
Read the original article
Hit count: 291
I am making a simple class that contains a StreamWrite
class Logger
{
private StreamWriter sw;
private DateTime LastTime;
public Logger(string filename)
{
LastTime = DateTime.Now;
sw = new StreamWriter(filename);
}
public void Write(string s)
{
sw.WriteLine((DateTime.Now-LastTime).Ticks/10000+":"+ s);
LastTime = DateTime.Now;
}
public void Flush()
{
sw.Flush();
}
~Logger()
{
sw.Close();//Raises Exception!
}
}
But when I close this StreamWriter in the destructor, it raises an exception that the StreamWriter was already deleted?
Why? And how to make it work such that when the Logger class is deleted, the StreamWriter is closed before deletion?
Thanks!
© Stack Overflow or respective owner