Many times I have seen code where they write a Class like this:
public class Detail
{
public Detail()
{
this.ColumnCtrl = new List<UserControl>();
}
public List<UserControl> ColumnCtrl { get; set; }
}
But if I only write the following – it works very fine also:
public class Detail
{
public List<UserControl> ColumnCtrl { get; set; }
}
Is there any reason to write my get-set Classes like in the first example?
Your first example initializes the
ColumnCtrlproperty to a value when theDetailclass is constructed, where your second one will be leftnull. If it isn’t initialized elsewhere you should expectNullReferenceExceptions.As long as you initialize the
ColumnCtrlproperty explicitly before use when using your second example, they are exactly the same thing.An alternative (though slightly more verbose) would be to lazily instantiate the
ColumnCtrlproperty to eliminate the overhead of instantiating it whenDetailis constructed: