Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Destructors in C#

The following code explains the Destructors in C#.
Destructors begin with ~ symbol followed by class name.
There should not be any parameters in the brackets.

Syntax:
  1. class A
  2. {
  3. ~A()
  4. {
  5. code;
  6. }
  7. }


Example:
  1. using System;
  2. using System.Text;
  3.  
  4. namespace forgetCode
  5. {
  6.  
  7. class A
  8. {
  9. ~A()
  10. {
  11. Console.WriteLine("Destruct instance of A");
  12. }
  13. }
  14. class B
  15. {
  16. object Ref;
  17. public B(object o)
  18. {
  19. Ref = o;
  20. }
  21. ~B()
  22. {
  23. Console.WriteLine("Destruct instance of B");
  24. }
  25. }
  26.  
  27.  
  28. class program
  29. {
  30. public static void Main()
  31. {
  32.  
  33. B b = new B(new A());
  34. b = null;
  35. GC.Collect();
  36. GC.WaitForPendingFinalizers();
  37. }
  38. }
  39. }


Output:

Destruct instance of B
Destruct instance of A

or

Destruct instance of A
Destruct instance of B

The output could be either because the language imposes no constraints on the order in which objects are garbage collected.