Class Destructor Problem
- by user279691
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!