views:

39

answers:

1

Hi All,

It is written in link http://msdn.microsoft.com/en-us/magazine/bb985010.aspx

"When an application creates a new object, the new operator allocates the memory from the heap. If the object's type contains a Finalize method, then a pointer to the object is placed on the finalization queue."

Can someone please clarify me

1) It means, only when we explicitly use finalize (using destructor) then object will go to finalize queue.

2) Every .NET class by implicitly using finalize (using destructor) so all .net class library object will go to finalize queue.

3)what about our custom class like classs A { } class A obj will go to finalize or not ,cosidering both cases (explicit/implicit destructor )

4) If above class is written in unmanaged code what will happen.It will go to finalize queue or not

Thanks

+1  A: 

Hi

1) Yes, objects which implement the Finalize()-method (the 'destructor' in C#) are added the the finalize-queue.

2) No, most of the .NET classes don't have Finalizer. When you don't implement one in your class, instances of that class won't be added to the finalize queue.

3) You class A will only go to the finalize-queue when it implements as Finalize-Method. (The 'destructor' in C#

4) Unmanaged class are not managed. The won't be garbage-collected nor added to the finalize-queue.

Some general notes.

  • The 'destructor' in C# isn't a destructor in the C++ sense. You've no grantees when it will be called etc. Its syntactic sugar for writing a finalizer-method.
  • Avoid finalizers, since they add addional overhead. First the object has to added to the finalize queue. Then it has to be garbage-collected twice. The first time to detect that it isn't used anymore. The second time when the finalizer-method has finished.
  • Use the IDisposable-interface for managing and freeing resources. Especially native resources.
  • Use the finalizer only, for 'emergency-clean-up' of native-resources. Basically you check if the object was disposed correctly (IDisposable)-interace. If not, you do the job in the finalizer to prevent further resource-leaks.
Gamlor