Constructors and Finalizers
                                                         
To establish an object's proper in-memory image, the runtime uses a
constructor.  By definition, the default
constructor takes no arguments.  If you do not explicitly define a constructor within your class, the compiler
automatically gives the class a default constructor.  The compiler provided default constructor faithfully "zeros"
the memory allocated for the object's use.


class Employee
{

  // Private keyword used for clarity.

  private string mName;
  private double mWage;
  private double mHours;

  // A custom constructor
 
  public Employee(string name)
  {
     mName = name;
  }
...
}



This code has two effects.  First, the compiler sees that you have provided your own constructor, so it does
NOT add a default constructor to your class.  Second, since the default constructor is gone, the original object
creation code we wrote is broken:


// Compiler Error! Trying to call the default ctor.

Employee emp2 = new Employee();

// This is line is OK.
    
Employee emp3 = new Employee("Homer");


If we want both of these lines of code to work, then we have to provide another version of the constructor.  In
other words, we must overload the constructor.  Method overloading will be examined in detail later.


class Employee
{
...
  public Employee(string name)
  {
     mName = name;
  }

  public Employee(){}

}


If the runtime calls the constructor when it creates an object, what does the runtime call when it destroys the
object?  The optimal answer is
nothing. In other words, it is best to design your objects such that no special
action is necessary when the runtime destroys the object.  However, if some action was required on object
destruction, then you would implement a
finalizer.

In C#, the finalizer syntax is identical to the C++ destructor syntax.  A finalizer is named after the class with a
tilde (~) prefix. For example: ~Employee.

Finalizers cannot take any arguments, cannot return a value and cannot be overloaded. Therefore, a class can
only have one finalizer.  Finalizers cannot take access modifiers. Instead they are implicitly protected.


class Employee
{

  // Finalizers look exactly like C++ destructors

  ~Employee()
  {

     // Put cleanup logic here.

  }
...
}

Constructors and Finalizers
Table of Contents
C# Tutorial | C#.NET Tutorial | Constructors Tutorial

Copyright (c) 2008.  Intertech, Inc. All Rights Reserved.  This information is to be used
exclusively as an online learning aid.  Any attempts to copy, reproduce, or use for training is
strictly prohibited.
Courseware
Training Resources
Tutorials
Services