Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate C# class in ASP.NET in page partial or within method

Tags:

c#

class

asp.net

I might not be explaining this clearly. But what are the drawbacks in creating the class inside the partial class vs. inside each method? (please see examples)

Example inside partial:

public partial class test: System.Web.UI.Page
{

cSystem oSystem = new cSystem();

protected void Page_Load(object sender, EventArgs e)
    {
    oSystem.useme();
}
protected void btnSubmit_Click(object sender, EventArgs e)
    {
    oSystem.usethis();
}

versus

Example inside each class:

public partial class test: System.Web.UI.Page
{


protected void Page_Load(object sender, EventArgs e)
    {
    cSystem oSystem = new cSystem();
    oSystem.useme();
}
 protected void btnSubmit_Click(object sender, EventArgs e)
    {
    cSystem oSystem = new cSystem();
    oSystem.usethis();
}
like image 336
user2156940 Avatar asked Jun 26 '13 20:06

user2156940


1 Answers

In most pages, there really wont be that big of a difference in practice.

The first example will create the instance when the Page is created. oSystem will be available for the entire lifetime of the page.

The second example will create the instance in the Page_Load event which doesn't happen until roughly the middle in the page lifecycle.

See ASP.NET Page Life Cycle Overview for more information on the page lifecycle.

If you wanted to use the instance earlier, in the Page_Init event for instance, then the former example wouldn't allocate the object earlier enough.

If your application needs to be high performance, requiring very efficient memory management, you would probably prefer the latter example. This example would allocate the memory closer to when it is being used so it wont be tying up resources longer than it needs to. That said, if you wanted efficient memory management, there are plenty of optimizations you could make.

So, in most pages, there isnt a practical difference.

like image 148
Jeff Avatar answered Oct 25 '22 14:10

Jeff