0

I have main class Form1:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

   public void GetLengthFirst_Click(object sender, EventArgs e)
   {
        textBox.Text = "123";
    }
}

and my own class:

class Arr
{
    /// in my opinion this should be done like this...
    int Lenght = Convert.toInt32(Form1.textBox.Text);
    int[] nums = new int[Lenght];
}

but my ideas did not materialize

Fred
  • 3,365
  • 4
  • 36
  • 57
Sasha Zuev
  • 29
  • 5
  • A form is like any other class. If you want to get a value from an instance of a class, you have to a) have a reference to that instance and b) make the value available (e.g. `public`). Anyway, your `Arr` class should not be referencing the form, it should just be told what the value of `Length` is and (presumably) what values will be used for the array. – stuartd Mar 18 '20 at 00:06
  • https://stackoverflow.com/a/60407914/591656 – CharithJ Mar 18 '20 at 00:20

1 Answers1

2

You can't access to the members of an another class if they aren't static. Also, the members must be public, or at least internal (can be accessed in the same assembly). Therefore, if the members are not static, you should tell to your second class where's your member. That's called class navigability.

So in your case :

public partial class Form1 : Form { 
   public Form1() {
        // tell to your second class where's your member
       Arr arr = new Arr(this);

       InitializeComponent(); 
   } 
   public void GetLengthFirst_Click(object sender, EventArgs e) { 
      textBox.Text = "123";
   }
 }

class Arr {
   private Form1 _form1;
   public Arr(Form1 f) {
      // Access to the members of your main class
      _form1 = f;

      int Lenght = Convert.toInt32(_form1.textBox.Text);
      int[] nums = new int[Lenght];
   }

}

Xavier Brassoud
  • 697
  • 6
  • 14