Budapest Budapest - 16 days ago 4
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.. (
Label
s,
TextBox
es).

But the
ViewPanel
and
EditPane
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 (
WrapPanel
) to be their parent and so I display the
ViewPanel
or
EditPanel
by adding it to the
ControlCollection
of the
WrapPanel
. So removing the panel is easy, if I write:

WrapPanel.Controls.Clear();


It will easily remove whichever panel is showing, but in order to add the desired panel (
ViewPanel
or
EditPanel
) 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
Form1
?

('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

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.