How to call one constructor from another in C#?
How to call one constructor from another in C#?
I completed my post-graduation in 2013 in the engineering field. Engineering is the application of science and math to solve problems. Engineers figure out how things work and find practical uses for scientific discoveries. Scientists and inventors often get the credit for innovations that advance the human condition, but it is engineers who are instrumental in making those innovations available to the world. I love pet animals such as dogs, cats, etc.
Aryan Kumar
13-Jul-2023Sure, here is how to call one constructor from another in C#:
To call one constructor from another in C#, you can use the
this()
keyword. Thethis()
keyword takes the name of the constructor that you want to call as a parameter.For example, the following code calls the
Constructor1()
constructor from theConstructor2()
constructor:C#
When the
Constructor2()
constructor is called, thethis()
keyword calls theConstructor1()
constructor first. Then, theConstructor2()
constructor sets thename
property.Here is an explanation of the code:
this()
keyword is used to call theConstructor1()
constructor.Constructor1()
constructor is the default constructor for theMyClass
class.Constructor2()
constructor takes astring
parameter calledname
.Constructor2()
constructor calls thethis()
keyword to call theConstructor1()
constructor.Constructor2()
constructor also sets thename
property.