Can someone expain, what sense of this construction?
public class A
{
public A(): this("..") {}
}
Can someone expain, what sense of this construction?
public class A
{
public A(): this("..") {}
}
: this(…)
after the constructor calls another constructor with the specified arguments. For example:
public class A
{
public A (string foo)
{
Console.WriteLine(foo);
}
public A () : this("foo bar")
{}
}
This will allow you to create an object of A
and pass a string to customize its output; or you can call it without arguments which causes the second constructor to be called which itself calls the first one with "foo bar"
as the argument.
There is one other similar keyword which is used when A
inherits from some other class. In that case, you can use base
instead of this
to directly call a constructor from the base class:
public class A : B
{
public A () : base("foo bar")
{}
}
So when you now create an object of A
, the constructor of A
will call a constructor of B
that accepts a string and pass "foo bar"
there.
For more information, see the “Using constructors” section of the C# programming guide.
If the parameter-less constructor is called it will call the constructor accepting a single string, passing ".."
. In your case there is no such constructor though, so the code wont compile.