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
{
    get
    {
        if (Res == null)
        {
            Res = GetDataTable();
        }
        return Res ;
    }
    private set;
}

      

against.

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 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.

+3


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.

+1


source


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.

0


source







All Articles