I am trying to better understand chaining of constructors in C# and I have run into the following issue.
class Item
{
private string _name;
private string _category;
private int _sku;
private double _price;
// default values
public Item()
{
_name = "";
_category = "Sale Item";
_sku = 123;
_price = 1.99;
}
public Item(string name, double price) : this()
{
this._name = name;
this._price = price;
}
public Item(string name, string category, int sku, double price)
{
this._name = name;
this._category = category;
this._sku = sku;
this._price = price;
}
public string Name
{
get { return this._name; }
}
public string Category
{
get { return this._category; }
}
public int SKU
{
get { return this._sku; }
public double Price
{
get { return this._price; }
}
}
My idea was to use the parameterless constructor to set default values and use the parametrized constructors to only change those values which need to be updated.
Unfortunately this does not work. The code does not compile. The error message is 1729: there is no constructor that takes 2 arguments. I realize that this is not how constructors are normally chained but I do not understand why this fails to compile as the parameterless constructor Item() is called first before the second constructor Item(string name, double price) is called.
Any insight and sugegstions would be greatly appreciated.