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 2

    1. The correct way: do not use global variables.
    2. 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?