Hello everyone,
For example, my class Foo wraps an object of StreamWriter, I must make Foo implements IDisposable and in the Dispose method of class Foo, invoke Dispose method of the StreamWriter object instance to release resource properly?
[Code]
using System.IO;
public class Foo : IDisposable
{
StreamWriter a;
public Foo()
{
}
public void Dispose
{
if (null != a)
{
a.Dispose();
}
}
}
[/Code]
thanks in advance,
George
George GeorgePosted Apr 15, 2008, 10:58 AM
Thanks Alan!
Cool! Question answered.
regards,
George
AlanPosted Apr 15, 2008, 10:33 AM
C#'s destructor and the protected virtual Finalize() method, which all classes inherit from System.Object, are in fact one and the same.
When you define a destructor for a class, the C# compiler replaces this with an override of the Finalize() method. In other words, if you have a class Test say, then this code:
~Test()
{
// do something
}
is (in effect) replaced with this before being converted to MSIL:
protected override void Finalize()
{
try
{
// do something
}
finally
{
base.Finalize();
}
}
Because of this, you're not allowed to override or call the Finalize() method directly in C# code - you always work via the destructor syntax which implicitly causes all the destructors higher up the inheritance chain to be called.
You're not allowed to call the destructor directly either. Instead, it's called by the system (unless it's been suppressed by a call to GC.SuppressFinalize) when there are no longer any references to the object and it can therefore be destroyed by the GC.
George GeorgePosted Apr 15, 2008, 9:00 AM
Thanks Nipun,
I have re-thought what is my question, let me ask in another more clear way. :-) What is the relationship between Finalize method and destructor?
Finalize will call destructor or vice versa? Or no relationship? GC will call Finalize, but I am not sure whether GC will call destructor as well?
regards,
George
Nipun TomarPosted Apr 15, 2008, 7:49 AM