I am new to CSharp.I have seen “this()” in some code.My question is Suppose if i call
Paremeterized constructor ,am i invoking the paremeterless constructor forcefully?.But According to constructor construction ,i believe parameterless constructor will be executed first.Can you please explain this with simple example so that i can get exactly when should i call “this()”.Thanks in advance.
public OrderHeader() { }
public OrderHeader(string Number, DateTime OrderDate, int ItemQty)
: this()
{
// Initialization goes here ....
}
By default (for classes), there is an implicit :base(), so it is always chaining something. Adding :this() calls the parameterless constructor of the current type, and so on – sooner or later it will call down to a base constructor of some kind. Yes, the :this(…) or :base(…) happens before the constructor body.
In the example shown, adding :this() does no harm, but does nothing useful either. In more complex scenarios, :this(…) is commonly used to avoid duplicating constructor code – usually directing all constructors to the most parameterized version – for example: