Reputation: 39
I am having trouble wrapping my head around this one. I have 2 constructors. The first has 2 arguments:
public Instrument(string name, string category)
{
this.Name = name;
this.Category = category;
}
Then I have a default(no argument) constructor with constants for defaults:
public Instrument()
{
this.Name = DefaultName;
this.Category = DefaultCategory;
}
I am also supposed to call the 2 parameter constructor from the no argument constructor. How do I do this? I also question why this is even necessary. If you are calling the 2 parameter from the default how would you ever pass the default values to the application? So I guess my main question is how do I call the 2 parameter constructor from the default constructor?
Upvotes: 2
Views: 4857
Reputation: 116
This is how you can do this...
public class Instrument
{
public string Name;
public string Category;
public Instrument()
: this("DefaultName", "DefaultCategory")
{
}
public Instrument(string name, string category)
{
this.Name = name;
this.Category = category;
}
}
Now to answer the question why this is even necessary....
This is to make sure that if you ever come across an instantiated object inside the code - doesn't matter how it was instantiated (using either of constructor) - it will always have valid values in it's properties Name & Category.
Basically, it potentially makes your business objects bug free. Anyone using your business object will always have valid values in it's properties - either default or passed in using 2nd constructor.
Upvotes: 2
Reputation: 4006
by calling the two arg constructor from the default one, passing the default values, like this:
public Instrument() : this(DefaultName, DefaultCategory)
{
}
Upvotes: 8