There are many many similar links in stackoverflow, all which seem to be addressing complex functions (so quite difficult for me to understand what i really should go for). But mine is simple. I just want to know if declaring a function as static right way to go, if i can manage the same functionality even with a nonstatic approach? Which approach utilizes more memory?
Here’s a sample code I’ve to implement, which is just showing up forms:
private void btn1_Click(object sender, EventArgs e)
{
Form1 frm = new Form1();
frm.ShowDialog();
}
Now I’ve to show this Form1 from many other forms in my program. So should it be better (right coding practice) to write the above piece of code where ever I want Form1 to be displayed, or should it be better to define it once as a static method in a static class, like this:
public static class globalvars
{
public static void Form1Show()
{
Form1 frm = new Form1();
frm.ShowDialog();
}
}
And then:
private void btn1_Click(object sender, EventArgs e)
{
globalvars.Form1Show();
}
I think if object of form is instantiated under the event where we want the form to be displayed (first non static approach), then the memory allocated for that process in the stack is destroyed right after its execution; while in the second static approach, the memory allocated stands throughout the lifetime of the application, and hence non-static approach is better right?
I know both works, and doesn’t make a big difference, but still, which is the right coding practice, memory usage wise?
Maybe I lost something there, but I didn’t see any difference between them. The
frmis a local variable, not a static field.