Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Without knowing exactly how to are trying to access the LinkedList, it's hard to say why it isn't working for you.</p> <p>Let's go over what you have. You have a LinkedList, which is an instance variable on a form. Since this LinkedList is an instance variable, it is associated with the instance of the form.</p> <p>This example below, will <strong>not</strong> work because it tries to access it statically:</p> <pre><code>public class MyForm : Form { public LinkedList&lt;string&gt; _list = new LinkedList&lt;string&gt;(); } public class MySecondForm : Form { public void Window_Loaded(object sender, EventArgs e) { MyForm._list.AddFirst("This doesn't work"); //WRONG! list is an instance variable we are trying to access statically. } } </code></pre> <p>So, we can see this does not work. We have a few options to get this working. First off, one very bad solution would be to actually make <code>list</code> static. Don't use this option. It's opens the door for concurrency problems, possibly leaking strong references, etc. Generally, using statics (like a singleton) I would discourage for passing data around for these reasons. The Singleton Pattern has a time and a place, but I don't think this is it since it can so easily be avoided.</p> <p>OK, since we got the bad solution out of the way, let's look at a few possible good ones.</p> <p>Set the list on <code>MySecondForm</code>. You have a few options for this. The constructor, a property, or a method. For example:</p> <pre><code>public class MyForm : Form { private LinkedList&lt;string&gt; _list = new LinkedList&lt;string&gt;(); public void Button1_Click(object sender, EventArgs e) { var secondForm = new MySecondForm(); secondForm.SetList(_list); secondForm.ShowDialog(); MessageBox.Show(_list.First.Value); } } public class MySecondForm : Form { private LinkedList&lt;string&gt; _list; public void Window_Loaded(object sender, EventArgs e) { this._list.AddFirst("This will work"); } public void SetList(LinkedList&lt;string&gt; list) { _list = list; } } </code></pre> <p>This is one possible solution. The constructor is another possible solution as <a href="https://stackoverflow.com/users/90272/billy">Billy</a> suggested.</p> <p>Because <code>LinkedList</code> is a reference type, any changes you make to it on the instance of <code>MySecondForm</code> will be reflected on the linked list of <code>MyForm</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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