Question
|
Difficulty Level:
3
|
Solution
|
Explanation Quality:4
|
The basic idea behind all these three methods is to give the object a chance to clean-up its state.
Generally this could be native resources that the object wants to let go off. Say a socket, a filestream
or a mutex.
Finalize can't be called by the programmer in code as only CLR calls it. The CLR runtime calls the finalize
method on the object. You can't know when the Finalize method will be called by the CLR. Moreover, you shouldn't
access any other object within the Finalize methods as they might have been finalized themselves.
Dipose on the other hand can be called to do the same job as the Finalize method, provided the type implements
the IDisposable interface. You can call Dispose from your code and its execution is deterministic.
Close is essentially the same as Dispose, the only difference is that it makes more sense to call Close on certain types.
For instance it sounds logical to say a filestream is closed than to say it is disposed.
The three methods are tied togather by the Dispose Pattern, which really tells you these methods work togather. Below is an
implementation. Note that the magic here is really that all Close, Dispose and Finalize methods call the Dispose(bool) method
here.
One very important thing to remember is that the object calling these methods doesn't give up it's owm memory, it's only
the resources that it uses that it's giving up. The memory for the object will be reclaimed by the GC.
|