How do destructors and garbage collection work in C#?

C# has finalizers (similar to destructors except that the runtime doesn't guarantee they'll be called), and they are specified as follows:

class C

{

~C()

{

// your code

}

public static void Main() {}

}

Currently, they override object.Finalize(), which is called during the GC process.

Showing Answers 1 - 11 of 11 Answers

pritam83

  • Sep 21st, 2007
 

use ~finalize() when you want to dispose the object reference forcefully...or better to say if you foind that destructor unable to destroy that object then use it.

  Was this answer useful?  Yes

pritam83

  • Sep 21st, 2007
 

If you are not declare any Main() method in your program then compiler will give you this errors. Basically Main() is the entry point for compiler for execution.

One more thing C# ia a case sensitive language so be carefull about the spelling of Main() method. If you mention main() instead of Main() then compiler will detect it as a constructor.

  Was this answer useful?  Yes

Destructors implicitly calls Finalize() method. It is advised not to used Destructors because when GC runs it pushes the object which has destructor in FinalizeQueue and clears the object from memory only when no other objects are there to be relaese from memory.

Basic features of destructors are:

·                  Destructors cannot be defined in structs. They are only used with classes.

·                  A class can only have one destructor.

·                  Destructors cannot be inherited or overloaded.

·                  Destructors cannot be called. They are invoked automatically.

·                  A destructor does not take modifiers or have parameters.

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions