Constructor

A constructor is a method that runs when a new instance of a class is created.
The job of the constructor is to create the object specified by a class and to put it into a valid state.
Constructors can be marked as public, private, protected, internal or protected internal.
If a field is marked as read-only then the only place in which it can be assigned is in the constructor.
A constructor is basically the class initialisation process
Two forms are supported
(1) inline field initializers
(2) constructors (constructor chaining also supported)


Instance and Static constructors supported
Static Constructors - called before types first use (also called type initializer)
Instance Constructors - called per-object allocation
A Copy Constructor creates a new object by copying variables from an existing object of the same type


Static Constructor

A static constructor is used to initialise any static fields, properties or events.
A static constructor can be used to perform an action that only needs to be performed once
It is called automatically before the first instance is created or any static members are referenced.
This allows you to control the initialization of static member data
Also referred to as a type initializer
A static constructor does not require any access modifier.
A class can only have one static constructor with no parameters.


public class MyClass 
{
   static MyClass()
   {
   }
}

Private Constructors

These are used to prevent creating instances of a class that do not have any instance fields or methods.
This is generally used in classes that contain only static members
It a class has one or more private constructors and no public constructor then it cannot be instantiated


Finalizer

Finalizers (historically referred to as destructors)
They are used to perform any necessary final clean-up when a class instance is being collected by the garbage collector.


Finalizer Method

These are associated with nondeterministic (not at any specific time) destruction of objects
You should avoid using one if at all possible.
In C# it is possible to implicitly overload Object.Finalize by using the tilde notation
The time and order of execution of a finalizer cannot be predicted or pre-determined
These run just before the garbage collector runs

class MyObject 

   ~MyObject()
   {
   }
}

There are very few situations where one of these is necessary
You should really only implement a finalizer if your object contains an unmanaged resource


It is good practice to include a Finalizer (that just calls the Dispose method) incase the Dispose method is not explicitly called.


If your class manages resources you should implement IDisposable
If your class creates any unmanaged resources you should implement IDisposable and also add a Finalizer.


Managed memory is automatically released by the garbage collector and does not need to be explicitly released.
Any unmanaged memory or resources however still need to be explicitly released.
System.Object declares a virtual method Finalize (or finalizer) that is called by the garbage collector before the memory is reclaimed.
This method can be overridden to release any unmanaged memory or resources.


Therefore relaying soley on a finalizer might not be appropriate in situations where it is important to reclaim the memory and resources as soon as possible.
The IDisposable interface provides a standard way of working with the Finalize method and can also be used for managed resources as well.



Dispose Method

These are associated with deterministic (at a very specific time) destruction of objects
You should implement the Interfaces > IDisposable interface and provide an additional Dispose method.
The C# compiler will not automatically call the Dispose method when the object goes out of scope
You must explicitley call the Dispose method.
Never use object references in a Dispose method.

class MyObject : IDisposable 
   MyObject()
   {
   }
  
   protected void Dispose()
   {
      Dispose(true);
      GC.SuppressFianlize(this);
   }
}

bool disposed = false;
protected virtual void Dispose(bool disposing)
{
    if (disposed == true)
    {
        return;
    }
    if (disposing == true)
    {
        //free any managed objects
    }

    //free any unmanaged objects
    disposed = true;
}


The reason for this is because .NET uses automatic garbage collection.
One disadvantage with this approach is called nondeterministic finalization which basically means that you don't know exactly when an object will be removed from memory.




GC.SuppressFinalize

This method tells the CLR not to call the finalizer for the specified object
If the object does not have a finalizer, calling this method has not effect
Object that implement IDisposable can call this method to prevent the garbage collector from calling the finalizer and therefore releasing the unmanaged resources.



GC.Collect

This forces garbage collection


GC.WaitForPendingFinalizers




Comparison with VB 6.0

VB 6.0 used a technique called reference counting to manage when an object was removed from memory.
This method kept track of how many variables were pointing to the object and when the last variable was set to Nothing, the object was removed from memory.
This method was called deterministic finalization because you always knew when the object was removed from memory.
One disadvantage of using this approach was that objects were often never removed in the situation when two objects were pointing to each other (creating a circular reference).



Primary

This allows you to use the class declaration to specify the most common constructor

class Person(string name, int age) 
{
   private string _name = name;
   private int _age = age;
}

instead of

class Person(string name, int age) 
{
   public Person (string name, int age)
   {
      _name = name;
      _age = age;
   }
}

Overloading


Instance Constructor

A class can have multiple instance constructors that can be overloaded
In C# we can supply parameters to constructors.
Having more than one constructor allows you to create the object with different parameters.
You must make sure each constructor has a unique signature.
The signature is composed of its name and its parameter list.

public class MyClass 
{
   public MyClass()
   {
   }

   public MyClass(string str)
   {
   }
}

Private Constructor

This is often used in classes that only contain static members.
When a class has one or more private constructors and no public constructors, other classes cannot create instances of this class.

public class MyClass 
{
   private MyClass()
   {
   }
}

Static Constructor

A static constructor can be used to initialize any static data (or perform actions that only need to be done once).

public class MyClass 
{
   static readonly string _initialize;

   static MyClass ()
   {
      this._initialize; = "only once";
   }
}

Copy Constructor

A copy constructor is not provided by default but you can easily add one.

public class MyClass 
{
   private string _internal;

   public MyClass (MyClass previousClass)
   {
      this._interna1 = previousClass._internal;
   }
}

Copy Constructor calling Instance Constructor

A copy constructor is not provided by default but you can easily add one.

public class MyClass 
{
   private string _internal;

   public MyClass(string param1)
   {
      this._internal1 = param1;
   }

   public MyClass (MyClass previousClass): this(previousClass._internal)
   {
   }
}

Calling A Different Constructor

It is possible for one constructor to invoke another constructor in the same object using the "this" keyword.
Lets imagine that we have 3 ways to create an object.
The first way is to pass in 1 parameters.
The second way is to pass in 2 parameters
The third way is to pass in 3 parameters.

public class MyClass 
{
   private string _internal1;
   private string _internal2;
   private string _internal3;

   public MyClass(string param1)
   {
      this._internal1 = param1;
   }

   public MyClass(string param1, string param2)
      : this(param1)
   {
      this._internal2 = param2;
   }

   public MyClass(string param1, string param2, string param3)
      : this(param1, param2)
   {
      this._internal3 = param3;
   }
}

Object Initializers


Allows you to instantiate and initialize objects in one compound statement
Let you assign values to any accessible fields or properties at creation without having to explicitly invoke a constructor

MyClass instance = new MyClass { MyField=10, MyProperty="text" }; 

instead of

MyClass instance = new MyClass(); 
instance.MyField = 10;
instance.MyProperty = "text";

this Keyword

You should use the "this" keyword when you want to refer to the instance itself


public class MyClass 
{
   private int _myInteger;

   public MyClass()
   {
      this._myInteger = 20;
   }

   public int Method_Multiply(int value1)
   {
      return value1 * this._myInteger;
   }
}

base Keyword

This type of constructor will call BaseClass.BaseClass
If you omit the call to the base constructor it will be called automatically
If there is no default (parameteless) base constructor then one must be called explicitly
The constructor for the base class is called before the block for the constructor is executed

public class DerivedClass : BaseClass 
{
   public DerivedClass() : base()
   {
   }
}

This is the same as

public class DerivedClass : BaseClass 
{
   public DerivedClass()
}

You can also use this to pass items between the derived and the base classes
This type of constructor will call BaseClass.BaseClass(string)

public class DerivedClass : BaseClass 
{
   public DerivedClass(string message)
   {
      base(message);
   }
}

vs

public class DerivedClass : BaseClass 
{
   public DerivedClass(string message) : base(message)
   {
   }
}

The base keyword can be used with or without parameters
Use base when there is inheritance and a parent class already provides the same arguments



© 2026 Better Solutions Limited. All Rights Reserved. © 2026 Better Solutions Limited TopPrevNext