Create an instance of a C # class in ASP.NET in a partial or inside method

I can not explain it clearly. But what are the disadvantages of creating a class inside a partial class and inside each method? (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(); } 

vs

An 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(); } 
+6
source share
3 answers

Most pages will not really make much difference in practice.

The first example instantiates when Page is created. oSystem will be available for the entire resource of the page.

The second example will create an instance in the Page_Load event, which will not happen until about the middle of the page life cycle.

For more information on the page life cycle, see ASP.NET Page Life Cycle Overview .

If you want to use the instance earlier, for example, in the Page_Init event, then the previous example will not select the object sooner.

If your application needs to be high-performance, requiring very efficient memory management, you will probably prefer the last example. In this example, the memory will be closer to when it will be used, so it will not bind resources longer than necessary. However, if you want efficient memory management, you can do many optimizations.

So, on most pages there is no practical difference.

+2
source

As soon as the scenario when creating a new instance for each method will be a problem if you need to save the state of the object outside the method area. In this case, the instance for each method would be wrong, but I assume this is not the case for you.

Something else that may be important to consider is that this particular object is difficult to create or not.

In most cases, it is only about taste, since from the point of view of performance this, as a rule, does not matter.

Probably the first scenario is more suitable if you create the same instance many times, and you could do the same job with the same global instance. Just not to repeat the same line of instantiation.

+1
source
  • In the first case, the cSystem class will be created only once for the request.
  • In the second case, the cSystem class will be created twice when you press the submit button, one in the Page_Load method and the other in the btnSubmit_Click method.
+1
source

Source: https://habr.com/ru/post/948169/


All Articles