Are class variables / objects valid?

I have a simple website built with asp.net. It usually only has 1 or 2 users at a time. My question is, is it okay to instantiate a class at the class level or should I create instances for each method. Here's an example. I have a class named Host with a name field and a mac field. In my code for a specific page. Is it okay to do this:

public partial class addhosts : Page
{
     private Host host = new Host();
     private HostDal dal = new HostDal();

     protected void myMethod()
     {
          host.Name = "myname"
          host.Mac = "mymac"
     }

     protected void btnSubmit_Click(object sender, EventArgs e)
     {
          dal.AddHost(host)
     }
}         

      

+3


source to share


4 answers


First, what you are talking about is more commonly referred to as global

versus variables local

.

For the simple case you provided, it would be better to create a variable on submit click. The reason is that the user loads the object but never raises a submit request, then you instantiated the host object in memory when not needed.

However, as many have said, it doesn't matter one way or another. But again, this is a simplified example. Global variables can be dangerous and are often avoided because they can be changed from anywhere in your class. If one method expects some value, which is then overridden, it can make it difficult to debug problems in more complex examples.

Here is a wikipedia article that echoes my point above:



They are generally considered bad practice precisely because of their nonlocality: a global variable can potentially be changed from anywhere (unless they are in protected memory or otherwise rendered read-only), and any part of the program can depend on it

To get rid of the globals you can do this (using object initializers)

protected void btnSubmit_Click(object sender, EventArgs e)
{
      var host = new Host
          {
              Name = "myname",
              Mac = "mymac"
          };
      dal.AddHost(host)
}

      

+2


source


It does not matter.



Each request for your page is separate and knows no other requests, so there is no chance of "conflict" with other requests.

+1


source


It's completely OK to have custom data as fields inside an ASP.Net page instance. Each visit to the page creates a new instance of the class Page

, so you won't find yourself in a situation where data is incorrectly distributed among users.

+1


source


This is great because a new class is created for each user (ASP.NET by design). It's on a separate thread as well, so even static variables would be acceptable in this scenario.

Greetings, Ivan

0


source







All Articles