Joydip Kanjilal
Contributor

My two cents on constructors in C#

opinion
May 26, 20164 mins
Software Development

Constructors in C# initialize the members of the class to which they belong and design your classes with elegance

Constructors are member functions or methods of a class that have the same name as the class name and are used to initialize the members of a class. Such methods are invoked when an instance of the class is created. Note that a struct can also have a constructor. However, unlike a class, you cannot have an explicit parameter-less constructor in a struct

Here’s the syntax you should follow to define a constructor for a class.

[modifier] name (parameters)

{

// usual code

}

The C# programming language provides support for the following modifiers when you create a constructor for a class.

  • public
  • protected
  • internal
  • private
  • extern

A few points to note

A constructor cannot be virtual and cannot return any value. OK, but what is a virtual method anyway? Virtual methods are used to implement late binding. You can declare a method as virtual by specifying the keyword “virtual” in the method signature. A virtual method allow subclasses of the type to override the method. A constructor of a class cannot be virtual while a destructor can be virtual. A constructor cannot be virtual primarily because the virtual table or vtable is not available in the memory when it is in execution.

Default constructor

A class provides a constructor be default — such a constructor is known as the default constructor. A default constructor for a class is invoked when the class is instantiated using the “new” operator but no argument is passed to the constructor while constructing the instance.

Constructors are called in the order of inheritance. In contrast, the destructors are called in the reverse order of inheritance. You can have overloaded constructors but not overridden constructors as constructors are not inherited.

Static constructor

The static keyword in the C# programming language allows you to define static classes and static members. A static object is one that persists in the memory till the time the application is in execution. Note that you can have a static constructor in either a static class or a non-static class. A static constructor in a class is used to initialize the static members of a class. The static constructor of a class is invoked the first time a static member of the class is assessed. A static constructor can only access static members of a class.

Note that a class can have one and only one static constructor, i.e., you cannot have overloaded static constructors for a class. A static constructor cannot accept any parameter and cannot have any access modifiers. Also, a static constructor is executed just once in an application domain — it is called when a static member of the class is accessed. You don’t need to create an instance of a class to invoke its static constructor.

Instance constructor

A non-static or an instance constructor is one that is executed when an instance of the class to which it belongs, is created. Instance constructors can have public, private, protected, external, or internal modifiers. Instance or non-static constructors of a class can be overloaded. Constructors can also be chained, i.e., you can invoke a base class constructor from a derived class constructor. In essence, a constructor of a derived class can call the constructor of its base using a method known as constructor chaining. Note that for obvious reasons, constructor chaining is supported only by the non-static constructors of a class. Non-static constructors can also be private. Such constructors when present in a class prevent the class from being inherited.

The following code snippet illustrates how you can have overloaded constructors in a class.

public class Employee

   {

       //Private members

       public Employee()

       {

           //This is the default constructor

       }

       public Employee(int employeeId)

       {

           //This is a one argument constructor.

       }

       public Employee(int employeeId, int departmentId)

       {

           //This is a two argument constructor.

      }

   }

Let’s now dig into some code. Consider the following class that contains a static and also an instance constructor.

class StaticClassDemo

   {

       static StaticClassDemo()

       {

           Console.WriteLine ("This is a static constructor.");

       }

       public StaticClassDemo()

       {

           Console.WriteLine ("This is an instance constructor.");

       }

   }

You can now create an instance of this class using the code snippet shown below.

static void Main(string[] args)

       {

           StaticClassDemo obj = new StaticClassDemo();

           Console.ReadLine();

       }

When this code is executed, you would observe that the static constructor is executed first, followed by the non-static constructor.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author