Is there is a difference between these two approaches ?
In this approach I am using the getter to initialize the DataTable
public DataTable Res
{
get
{
if (Res == null)
{
Res = GetDataTable();
}
return Res ;
}
private set;
}
vs.
In this approach I am using the constructor to initialize the DataTable
public class XYZ
{
public DataTable Res{ get; private set;}
//constructor
public XYZ()
{
Res= GetDataTable();
}
}
This variable is used on an ASP.net page to fill a DropDown List. Which will perform better ?
Edit:-
This is used in a web application where data will not change. I bind this table to a dropdown list in Page_Load event.
The question is whether a given instance of class
XYZwill always need and use theDataTable.If not, then you’d want to lazy-initialize (using your getter), so as to avoid doing the work up front for nothing.
If you will always need it, then the next question is whether there is potentially any substantive delay between instantiation of the class and a call to the
Resproperty. If so, then loading the data upon instantiation could mean your data is a bit more stale than it would be if you waited until the property getter is called.The flip-side to that is not necessarily applicable in a web scenario, but in other applications one would want to consider whether a call to the property needs to be highly responsive to keep the UI from freezing. Preloading the data might be preferable in such a scenario.