Is it bad practice to put most variables at class level in a Form? Would these be considered global variables?
public partial class Form1 : Form
{
private string mode;
private int x, y;
public Form1()
{
InitializeComponent();
}
}
I’m using the variables in multiple controls when I declare them at class level.
Those would be considered class-level globals (to distinguish from application globals.) The more important distinction in this case is that they are
privateto the class.Class-level globals have their uses, so I definitely wouldn’t call it a bad practice. A very good use for private class globals is when you plan to expose them through property accessors. For example:
public readonlyproperties whose values are controlled by logic internal to your class.publicproperties with bothsetandgetaccessors (enabling custom validation logic in setter.)However, I would say it’s a good practice to make things local unless otherwise necessary. The reason is that you have less mutable state belonging to a class instance, so there is less potential for bugs like this: