Hello everyone,
I have a static class which wraps a file stream object. And I want to implement the
Dispose pattern. I define an uninitialize method in the static class which call Dispose
explicitly with parameter value true. Here is my code,
My questions are,
1. Normally there should be a destructor in a class which calls Dispose with parameter
value false, but for a static class, there is no concept like destructor, how to implement
calling Dispose with false parameter?
2. When the Dispose method without parameter will be called?
3. Is it correct to call GC.SuppressFinalize(this)? Since for a static class, there is no "this"
object?
4. Correct to define disposed as static field?
5. Are there anything wrong with my code?
[Code]
static private StreamWriter currentLogStream;
private static bool disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private static void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if (false == disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if (disposing)
{
// Dispose managed resources.
currentLogStream.Dispose();
}
}
disposed = true;
}
public static void Uninitialize()
{
Dispose(true);
}
[/Code]
thanks in advance,
George
Bechir BejaouiPosted Dec 3, 2008, 10:13 AM
Ryan AlfordPosted Dec 2, 2008, 3:36 PM
Bechir BejaouiPosted Dec 2, 2008, 3:24 PM
Ryan AlfordPosted Dec 2, 2008, 9:05 AM
2. Normally, the Dispose() method(without the parameter) will be called when you are finished with the instance of the class. However, since your class is static and you never explicitly create an instance of it, I don't know when the Dispose will be called.
3. There is really no reason to implement the IDisposable interface with a static class. Just more code that is irrelevant.
4. No.
5. Other than declaring everything as static, your code is close to being correct. Remove all of the "static"s from the class, then add a deconstructor. Then you code will have correctly implemented the IDisposable interface.
Bechir BejaouiPosted Dec 1, 2008, 8:51 AM