To call one constructor from the body of another in C#, you can use the
this() keyword. The this() keyword refers to the current object.
The following code shows how to call one constructor from the body of another:
C#
class Person {
public Person() {
// This is the default constructor.
}
public Person(string name) {
// This constructor takes a name parameter.
this(); // Call the default constructor first.
this.Name = name;
}
public string Name { get; set; }
}
In this example, the Person() constructor is the default constructor. The
Person(string name) constructor takes a name parameter. The first line of the
Person(string name) constructor calls the Person() constructor first. This is done to ensure that the fields of the
Person class are initialized before the name property is set.
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To call one constructor from the body of another in C#, you can use the
this()keyword. Thethis()keyword refers to the current object.The following code shows how to call one constructor from the body of another:
C#
In this example, the
Person()constructor is the default constructor. ThePerson(string name)constructor takes a name parameter. The first line of thePerson(string name)constructor calls thePerson()constructor first. This is done to ensure that the fields of thePersonclass are initialized before the name property is set.