Element initialization in Getter or Constructor

Is there a difference between the two approaches?

In this approach I am using a getter to initialize the DataTable

public DataTable Res
        if (Res == null)
            Res = GetDataTable();
        return Res ;
    private set;



In this approach I am using the constructor to initialize the DataTable

public class XYZ
    public DataTable Res{ get; private set;}
    public XYZ()
        Res= GetDataTable();            


This variable is used in the ASP.net page to populate the DropDown list. What will be better?

Edit: -

This is used in a web application where the data will not change. I bind this table to the dropdown on the Page_Load event.


source to share

2 answers

The question is whether you always need a given instance of the class XYZ

and use DataTable


If not, then you want to lazy-initialize (using your getter) so you don't have to do the work ahead for anything.

If you always need this, the next question is whether there is a potential significant delay between class creation and property invocation Res

. If so, loading the data after instantiation might mean that your data is a little simpler than it would be if you were waiting for the getter to be called.

The flip side to this is not necessarily applicable in web scenarios, but in other applications I would like to consider whether to react to a property so that the UI is dependent on hovering. Data preloading may be preferable in such a scenario.



Yes, there is a difference. The first method is called a lazy instance, which means that you wait until the object has been used before creating it. The best part about this is that you wait until the last second is able to use the memory and processor needed to configure the object.

The second method instantiates the object immediately after the class is created. The downside to this is that if you never use that object, you wasted time creating the object and memory during object allocation.



All Articles