C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
They create instances of classes with runtime support. They are standardized initialization methods. We invoke a constructor with the new-keyword.
Example. This program shows the syntax for a public constructor with one formal parameter. In the Main method, it shows how to invoke this constructor to create new instances of the Widget type.
Widget: A Widget is a term for a "thing." It is often employed by lazy example writers in documentation.
Result: The program creates a Widget with size 10, and then another with size 20.
Based on: .NET 4.5 C# program that uses constructor 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); } }
Base. 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.
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.
Tip: Making code easy to read and understand should be a design goal for many classes.
Default. 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.
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: A private constructor must be used within methods on the class. The class can be invoked within a factory method.
Public: Most constructors are public. This lets you create a class instance from anywhere in the program.
C# program that uses public fields 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; } } C# program that uses constructor 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. We tested whether the two approaches shown in the previous example had different performance. 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]
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 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.
Note: Destructors may be useful in certain situations. Usually they are not. They should be seldom used.
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.
Caution: A static constructor can slow down accesses to the members of a class. This is hard to test.
Strings are a special type in the .NET Framework. Usually you need no constructor when using them. But a string constructor exists, and it is used to transform a char array to a string, or create strings with repeating values.
Research. In my research, I found that constructors are a standardized form of init() methods. Language designers felt that using init() is "inelegant." So constructors, a special syntax form, were introduced.
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.
Summary. There are many kinds of constructors in the C# language. We experimented with constructors. We use constructors to make code clearer. With them, we formalize how objects are created.