C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
It is used to overload the constructors in a C# program. It allows code to be shared between the constructors. Constructor initializers, which use the this-keyword, prove useful in nontrivial classes.
Example. This program contains a class called Mouse with two public constructors. The first constructor is parameterless and it calls into the second constructor, using this-constructor initializer syntax.
The this-keyword in this context instructs the compiler to insert a call to the specified constructor at the top of the first constructor. The target constructor is determined through the process of overload resolution.
C# program that uses overloaded constructor initializer using System; class Mouse { public Mouse() : this(-1, "") { // Uses constructor initializer. } public Mouse(int weight, string name) { // Constructor implementation. Console.WriteLine("Constructor weight = {0}, name = {1}", weight, name); } } class Program { static void Main() { // Test the two constructors for Mouse type. Mouse mouse1 = new Mouse(); Mouse mouse2 = new Mouse(10, "Sam"); } } Output Constructor weight = -1, name = Constructor weight = 10, name = Sam
We see the this-keyword in the context of a constructor. To use the this-keyword, specify it after a colon following the parameter list. The constructor name must match that of the declared class where you are adding it.
Tip: The this() syntax instructs the compiler to insert the specified constructor that matches the parameter list specified.
In the program, the parameterless constructor to the Mouse class passes in the values -1 and an empty string literal to the second constructor. When the program is executed, the constructor specified by "this" will be called.
So: The C# compiler inserts the inner constructor call at the top of the first constructor call.
Base. Also, you can add the base() syntax to specify that a constructor calls into the constructor from the class from which it derives. The parameters of the base call must match. Base has similar syntax as the this-constructor.
Note: The language provides a default constructor as well, which implicitly calls into the base constructor.
Summary. A constructor initializer enables overload resolution to occur on a constructor and a custom type. It allows code sharing between constructors and overloaded constructors. And it reduces code size and improves type usability.