Using a Destructor - CSharp Custom Type

CSharp examples for Custom Type:Finalizer

Introduction

A C# destructor is defined by using a tilde (~) followed by the class name and empty parentheses.

For example, the destructor for an xyz class is as follows

~xyz()
{
  // Destructor body
}

There are no modifiers or other keywords to be added to a destructor.

Demo Code

using System;/*from  w ww.ja  v a2  s .c om*/
public class test
{
   static public int si = 0;
   public int i = 0;
   public void routine()
   {
      Console.WriteLine("In the routine - i = {0} / si = {1}", i, si);
   }
   public test()
   {
      i++;
      si++;
      Console.WriteLine("In Constructor");
   }
   ~test()
   {
      Console.WriteLine("In Destructor");
   }
}
class TestApp
{
   public static void Main()
   {
      Console.WriteLine("Start of Main function");
      test first = new test();
      test second = new test();
      first.routine();
      test third = new test();
      third.routine();
      second.routine();         // calling second routine last
      Console.WriteLine("End of Main function");
   }
}

Result


Related Tutorials