I have an array of buttons with which I work through some methods, and in each of them I have to recreate (Button [,] buttons = new Button [,] {...}) this array to work with it. Is it possible to make this array a global variable?
2 answers
- The correct way: do not use global variables.
- A bad way: to declare in any one class (which will be visible from the necessary methods) a static variable (or property) of the desired type.
- four+1 for the first method. Global variables are evil! - VladD
As mentioned earlier, global variables are bad. But it all depends on how global they are, namely, what is the scope.
For example, we have a form class, inside which there are methods in which an array of buttons is needed, to which we periodically appeal, will look something like this:
public partial class MainWindow : Window { private Button[,] buttons; // ΠΌΠΎΠΆΠ΅Ρ Π±ΡΡΡ Button[]? public MainWindow() { InitializeComponent(); buttons = new Button[,] {...} // ΡΡΡ ΠΌΡ ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·ΠΈΡΡΠ΅ΠΌ Π½Π°Ρ ΠΌΠ°ΡΡΠΈΠ² (ΠΊ ΠΏΡΠΈΠΌΠ΅ΡΡ) } private void button_Click(object sender, RoutedEventArgs e) { // Π²Π½ΡΡΡΠΈ ΠΌΠ΅ΡΠΎΠ΄Π° ΠΌΡ ΠΊΠ°ΠΊ-ΡΠΎ ΡΠ°Π±ΠΎΡΠ°Π΅ΠΌ Ρ Π½Π°ΡΠΈΠΌ ΠΌΠ°ΡΡΠΈΠ²ΠΎΠΌ ΠΊΠ½ΠΎΠΏΠΎΠΊ } private void button1_Click(object sender, RoutedEventArgs e) { // Π²Π½ΡΡΡΠΈ ΠΌΠ΅ΡΠΎΠ΄Π° ΠΌΡ ΠΊΠ°ΠΊ-ΡΠΎ ΡΠ°Π±ΠΎΡΠ°Π΅ΠΌ Ρ Π½Π°ΡΠΈΠΌ ΠΌΠ°ΡΡΠΈΠ²ΠΎΠΌ ΠΊΠ½ΠΎΠΏΠΎΠΊ } } Gave a primitive example where buttons visible within the MainWindow . In this form, it still does not look as scary as it could be. Therefore, in your case it is necessary to choose the optimal scope of the variable .
And yet, in principle, you can write a method that will return you a list of buttons lying on a particular component, here is an example . Of course, this may not be suitable for solving your problem, but I dare to offer you as an example for your reference.
PS: Button[,] is a two-dimensional array (taken from your question), does it make sense to use the one-dimensional Button[] array?