Budapest Budapest - 1 year ago 107
C# Question

Static class vs. static variables best practice

I use WinForms. In this app I can show a VIEW MODE and an EDIT MODE, both these modes will display a different panel (

Panel ViewPanel
Panel EditPanel

They both are only created ONCE, and they both contain other controls.. (

But the
l are not shown at the same time, so I need to be able to remove one and add the other so the user can see it.

In other classes I have functions & events that interact with, and may change, the mode from "Edit" to "View" so I would need to show or remove those panels.

I have created a panel (
) to be their parent and so I display the
by adding it to the
of the
. So removing the panel is easy, if I write:


It will easily remove whichever panel is showing, but in order to add the desired panel (
) to the wrap I need to reference it from other classes (that have events and functions that may need to change the display from "Edit" to "View").

So having these panels declared somewhere as 'static' seems to make it easy to reference these panels from any class.

[I read in some forums to avoid making static classes, not sure exactly why and I wonder if this pertains to static variables too.]

Is it best practice to just declare these variables as static variables in

('public partial class Form1' is the default opening class for all WinForms apps)

Or is it better practice to make another (non-static) class
-for example:

public class VarClass

and declare the Vars there as:

public Static Panel ViewPanel;
public Static Panel EditPanel;

Or 3rd option to make a static class - for example:

public static class StaticVarClass

and declare variables there (also with 'public static' keyword)

What is the best practice for performance and/or what are pro's & con's of each?

Answer Source

If you don't create object of some class and this class contains some constants for using globally you should create static class. If object of the class is not needed your choice should be a static class.

If your variables are related to some functionality only you should create class with static variables. Sometimes you want to create objects of some class and share some info among this objects, the best case will be to create non-static class with static shared variables.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download