C# Constructor Tips

Class Constructor

New keyword (constructor invocation)

Classes are conceptual units. With them we construct object models. And constructors are specialized methods that have runtime support to create instances of classes for these models. They use a special C# syntax form.

The use of functions such as init() to provide initialization for class objects is inelegant and error-prone.... A better approach is to allow the programmer to declare a function with the explicit purpose of initializing objects. Stroustrup, p. 226

Example

This program shows the syntax for a public constructor with one formal parameter. In the Main method, it shows how you can invoke this constructor to create new instances of the Widget type.

Program that uses constructor [C#]

class Widget
{
    int _size;
    public Widget(int size)
    {
	this._size = size;
    }
}

class Program
{
    static void Main()
    {
	Widget widget1 = new Widget(10);
	Widget widget2 = new Widget(20);
    }
}

Result
    1. It creates a Widget with size of 10.
    2. It creates another Widget with size of 20.

Base

Base keyword

If you have to add a constructor to a derived class, the base keyword is often useful. This will have the derived constructor invoke the base class constructor—with the specified argument.

Base

This

Sometimes in a class you have many different constructors. You can use the "this" keyword to have one constructor invocation call another constructor method. This reduces code bloat.

This

Default constructor

Note

Every public class has a default constructor. This is inserted by the C# compiler and is not shown in the C# code. It receives no parameters. It has no internal logic. It is removed if you add an explicit constructor.

Default Constructor

Instance constructors

Instance constructors are the most common. Let's look at two common patterns that developers use to initialize member variables in classes. The first pattern sets the fields directly. The second uses a special overloaded constructor.

Private Constructor Public Constructor New
Program that uses public fields [C#]

using System;

class Program
{
    class C1
    {
	public int A;
	public int B;
	public C1()
	{
	}
    }

    static void Main()
    {
	C1 c = new C1();
	c.A = 1;
	c.B = 2;
    }
}

Program that uses constructor [C#]

using System;

class Program
{
    class C2
    {
	int A;
	int B;
	public C2(int a, int b)
	{
	    A = a;
	    B = b;
	}
    }

    static void Main()
    {
	C2 c = new C2(1, 2);
    }
}

Benchmark

Performance optimization

We tested whether the two approaches shown in the previous example had different performance characteristics. The results were that class C2 was more efficient. We used a tight loop that instantiated many instances.

Code benchmarked for constructor C1 [C#]

C1 c = new C1();
c.A = i;
c.B = i + 1;

Code benchmarked for constructor C2 [C#]

C2 c = new C2(i, i + 1);

Results
    100000000 iterations were benchmarked.

C1 Assign at caller:       557.6 ms
C2 Overloaded constructor: 507.6 ms [faster]

Results. The results show that the overloaded constructor C2 is more efficient. To investigate further, we can look at the MSIL instructions. You will find that the class C1 code has more instructions related to the evaluation stack.

MSIL
MSIL code example for C1

L_001c: stloc.3
L_001d: ldloc.3
L_001e: ldloc.2
L_001f: stfld int32 Program/C1::A

MSIL code example for C2

L_000d: ldarg.0
L_000e: ldarg.2
L_000f: stfld int32 Program/C2::B

Destructor

The C# language is garbage-collected: you do not need to manually free memory. But in certain cases, types need to execute statements when they are no longer used. This often involves unmanaged system resources. Destructors may be useful in certain situations.

Destructor

Static constructor

Static illustration

Static constructors are also called type initializers. They can execute instructions when a type is first accessed. Conceptually this resembles lazy instantiation. The time at which the static constructor executes is not guaranteed.

Static Constructor

Types and instances

There is a big difference between types and instances in computer programs, even though at first glance the two share the same part of your source code.

Type Versus Instance

Summary

The C# programming language

There are many different kinds of constructors in the C# language. In the experiment, we found instance constructors that receive arguments to initialize classes are faster than explicit assignments to public fields. Constructors can be used to make your code clearer and also improve its efficiency.

.NET