Reputation: 1695
what are the advantages of calling one constructor by other if there are multiple constructors? Thanks
Upvotes: 0
Views: 1211
Reputation: 45101
Looking at the already posted answers i will just they that you always walk the way from the default constructor down to the most specialized constructor. Trying to do the same the other way around always leads to code duplications or problems:
The good way:
public class Foo()
{
public Foo()
: this(String.Empty)
{ }
public Foo(string lastName)
: this(lastName, String.Empty)
{ }
public Foo(string lastName, string firstName)
: this(lastName, firstName, 0)
{ }
public Foo(string lastName, string firstName, int age)
{
LastName = lastName;
FirstName = firstName;
Age = age;
_SomeInternalState = new InternalState();
}
}
The bad way:
public class Foo()
{
public Foo(string lastName, string firstName, int age)
: this(lastName, firstName)
{
Age = age;
}
public Foo(string lastName, string firstName)
: this(lastName)
{
FirstName = firstName;
}
public Foo(string lastName)
: this()
{
LastName = lastName;
}
public Foo()
{
_SomeInternalState = new InternalState();
}
}
The problem of the second example is that the part what to do with all the parameters is now cluttered over all constructors, instead implemented in just one (the most specialized). Just imagine you like to derive from this class. In the second example you have to override all constructors. In the first example you only have to override the most specialized constructor to get full control over every constructor.
Upvotes: 3
Reputation: 10243
I used it when I want to pass default or null values to the other constructors. In the case above the user does not have to pass null when calling the constructor-- they can call it with nothing.
public class Widget(){
public Widget() : this(null){
}
public Widget(IRepository rep){
this.repository = rep;
}
}
Upvotes: 1
Reputation:
If you want to pass default values to a base constructor.
public class YourClass
{
private int SomeInt;
public YourClass() : this(0)
{
// other possible logic
}
public YourClass(int SomeNumber)
{
SomeInt = SomeNumber;
}
}
This follows the DRY principle (Don't Repeat Yourself). A simple example, but it should illustrate the idea.
Upvotes: 1
Reputation: 26737
the same advantages you get when you do method overloading : you don't repeat the same code
public class Person
{
public Person(string name,string lastName )
{
Name = name;
LastName = lastName;
}
public Person(string name, string lastName,string address):this(name,lastName)
{
//you don't need to set again Name and Last Name
//as you can call the other constructor that does the job
Address = Address;
}
public string Name { get; set; }
public string LastName { get; set; }
public string Address { get; set; }
}
Upvotes: 6
Reputation: 4032
You don't repeat yourself.
A change in implementing one constructor also affects all the other constructors, instantly. Copy and Pasting code is bad and should be avoided.
Upvotes: 8