Title may sound confusing. What I want is to call a constructor of the same class and the constructor of the base class inside a constructor. Maybe my first attempt to solve that may explain my question:
public MyClass(MyClass obj) : base(obj),this() {}
But that notation isn't working. Is there any solution to solve that?
The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java. If we have to call a constructor within the same class, we use 'this' keyword and if we want to call it from another class we use the 'super' keyword.
Calling a constructor from the another constructor of same class is known as Constructor chaining. The real purpose of Constructor Chaining is that you can pass parameters through a bunch of different constructors, but only have the initialization done in a single place.
Order of constructor call for Multiple Inheritance For multiple inheritance order of constructor call is, the base class's constructors are called in the order of inheritance and then the derived class's constructor.
No, you can't do it for the following reason:
When a constructor calls the constructor of its base, the latter call is THE PART of the constructor in question. So you can't call another constructor of the same class AND a constructor of a base class because the former call already contains a call to a base constructor - you can't initialize your base twice
C# allows either base(...) or this(...), because every constructor must eventually invoke a super constructor. So if it were possible to invoke both base() and this(), two super constructors invocations would take place, which would be fundamentally incorrect.
It is the same reason why it is not possible to invoke base(...) twice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With