TheDeveloperBlog.com


C# Default Constructor

Default constructor. Classes have default constructors. These constructors are injected into all class declarations that do not introduce other constructors. The default constructor provides a simpler syntax for type definitions. It is an important detail.


Example. This program shows how the default constructor is added to all classes that have no explicitly defined constructors. If no constructor is specified, a hidden one is automatically generated.

Tip: You can call the default constructor anywhere. It is a public parameterless instance constructor.

Public
C# program that uses default constructor in class

using System;

class Test // Has default parameterless constructor
{
    public int Value { get; set; }
}

class Program
{
    static void Main()
    {
	// Call the default constructor
	Test test = new Test();
	test.Value = 1;
	Console.WriteLine(test != null);
    }
}

Output

True

In this program, the Test class actually has a constructor. The Program class also has a default constructor. Each of these constructors is present in the compiled programs and you can call it with new Test() or new Program().

Also: Further in this article, you can see what the C# compiler actually generates for this constructor.


Internals. In the .NET Framework, C# code is compiled into a disk-based intermediate representation. The default constructors in this program are added there. We see next the intermediate language of the default constructor that was silently added.

Note: This constructor is invoked in the Main method. It calls into the base class constructor, which is the System.Object constructor.

IL
Test constructor: IL

.method public hidebysig specialname rtspecialname
    instance void .ctor() cil managed
{
    .maxstack 8
    L_0000: ldarg.0
    L_0001: call instance void [mscorlib]System.Object::.ctor()
    L_0006: ret
}


Summary. We looked at default constructors. We used a default constructor in a program. You can eliminate the default constructor from a class by specifying a private constructor, which eliminates external creation of the type.

Private Constructor

So: The default constructor injection reduces the size of C# source code. It does not negatively impact execution.