tags:

views:

38

answers:

2

Below is the sample code of one of my class:

#region Constructors
public ItemMaster()
{  }

public ItemMaster(string argItemName, string argItemCode, decimal? argStockInHand, decimal? argAlertLevelQty, string argUnit, decimal? argDiscount, string argWhetherInPercent, int argCategoryID)
{
    this.ItemName = argItemName;
    this.ItemCode = argItemCode;
    this.StockInHand = argStockInHand;
    this.AlertLevelQty = argAlertLevelQty;
    this.Unit = argUnit;
    this.Discount = argDiscount;
    this.WhetherInPercent = argWhetherInPercent;
    this.CategoryID = argCategoryID;
}
#endregion

When to use the former (the blank one there) and when to use the latter? If I leave it just blank inside brackets, but do pass the parameters, will it work?

+1  A: 

No it won't unless you define it like:

var ItemMaster = new ItemMaster() { ItemName = "NewItem" , CategoryID = 2 };  

However I prefer overloading the c'tor whenever I want to instantiate some properties upon object creation.

Kamyar
+1  A: 

The constructor with parameters is just a convenient way to initialize the properties/fields to a non default value. It is (usually) the same as calling the parameterless constructor and then manually assigning the properties.

If I leave it just blank inside brackets, but do pass the parameters, will it work?

It will works as written, i.e. the properties will be initialized to the default value and not to what you passed in, since you don't assign the parameters to the fields/properties. So it doesn't work as you want it to work.

The parameterless constructor is required for some deserializers. And structs always have a non overridable parameterless constructor.

For immutable types you need the constructor with parameters, since you can't change the fields/properties after construction.

CodeInChaos