public class abc
{
public abc():this(new pqr())
{}
}
The above code represents that the constructor abc() is inherited by some class.
What does the above code mean?
When to use such code?
Why it is used?
The above code represents that the constructor abc() is inherited by some class.
No it doesn't.
It means that the parameterless abc
constructor chains to the abc
constructor taking a pqr
.
So you'd actually have:
public class Foo
{
public Foo() : this(new Bar())
{
}
public Foo(Bar bar) // implicit call to parameterless base constructor
{
// Do something with bar here
}
}
See my article on constructor chaining for more info.
As for when you would want to do this - that's really too broad a question. But as an example, suppose you have a TimeOfDay
type - you may well want constructors of:
public TimeOfDay(int hour, int minute)
public TimeOfDay(int hour, int minute, int second)
public TimeOfDay(int hour, int minute, int second, int millisecond)
See more on this question at Stackoverflow