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)
}
}
source to share
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)
}
source to share