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:
public Foo() : this(27, "abc") {} // default values
public Foo(int x, string y) {...validation, assignment, etc...}
Well, you should use this()
if you want to call the parameterless constructor, it's as simple as that.
For example, if you have two constructors, where the parameterless initializes Id
and the parameterfull also initializes Name
, you should use this
, so that you don't repeat yourself:
public Foo()
{
Id = ComputeId();
}
public Foo(string name)
: this()
{
Name = name;
}
On the other hand, if the paramterfull constructor is a different way to initialize the Id
, you don't have to call this()
:
public Foo()
{
Id = ComputeId();
}
public Foo(int id)
{
Id = id;
}
This syntax is also not limited to the parameterless constructor, you can call any other constructor the same way:
public Foo(int id, string name)
: this(id)
{
Name = name;
}
Parameterless constructor will not be executed first by default - compiler will use only the constructor you're invoking explicitly. If you need to invoke the parameterless constructor for some reason then use this()
.
You can see the difference in the example below if you remove this()
.
class Test
{
public int x;
public int y;
public Test()
{
x = 1;
}
public Test(int y) : this() // remove this() and x will stay 0
{
this.y = y;
}
class Program
{
static void Main(string[] args)
{
var t = new Test(5);
Console.WriteLine("x={0} y={1}", t.x, t.y);
}
}
As was mentioned in another answer - the rule to invoke the parameterless constructor first applies to the base()
keyword. If you don't provide which base constructor to invoke then the compiler will attempt to invoke the parameterless one.
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