Note that there are some explanatory texts on larger screens.

plurals
  1. POwhat does a private variable really mean?
    text
    copied!<p>I have a form called form1 and I also have a class called class1 when I tried to get the text in a textbox in form1 from class1. it literally took me two days to figure out the correct way to get the text.</p> <p>see code below:</p> <p>I have the following class:</p> <pre><code>class Class1 { // field to hold the Form1 object reference private Form1 DataEntryForm; // Class1 constructor public Class1(Form1 form) { // store the Form1 object reference DataEntryForm = form; } public void gettext() { //the following doesn't work.. string textintextbox = DataEntryForm.textBox1.text; //I get the following error =&gt; somenamespace.Form1.textBox1 is inaccessible due to its protection //but the following code works just fine.... why? textintextbox = ((TextBox)DataEntryForm.Controls.Find("textBox1",true).FirstOrDefault()).Text; } } </code></pre> <p>as you can see I knew i had to declare a reference to the form in class1 and then access the textbox like so 'myform1refence.textbox1.text" but if you look at the code above this didn't work as the textbox1 is private. so i Google like I was possessed for workaround to this and everywhere I went, people suggested I "SHOULD NOT" make The textBox1 public as it's bad programming or something but i Should create a public variable like so </p> <pre><code> public partial class Form1 : Form { public sometype somevariablename {get { return somePrivatevariablename; } set { somePrivatevariablename = value; }} } </code></pre> <p>so I thought this is the correct way I should access my textbox1 from class1 so I wrote the following </p> <pre><code> public partial class Form1 : Form { public TextBox _textBox1 {get { return this.textBox1; } set { this.textBox1 = value; }} } </code></pre> <p>so when I type the following in class1 it works!</p> <p>exhibition A</p> <pre><code> string textintextbox = DataEntryForm.textBox1.text; </code></pre> <p>so for a day i went on coding and accepted this to be the best solution to my problem. Then by accident i stumbled onto the following code:</p> <p>exhibition B</p> <pre><code> string textintextbox = ((TextBox)DataEntryForm.Controls.Find("textBox1",true).FirstOrDefault()).Text; </code></pre> <p>with the above code I didn't need to make textbox1 public on create a public getter and setter for textBox1 all I needed to do was create a form1 reference.</p> <p>So my question is why does exhibition B work with only a reference to a form but exhibition A needs both a reference to the form and the the variable being accessed to be public to work. why is this...what I am missing?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload