Search code examples
c#arrayslistclassinstances

C# Storing class instances in an array to use in other forms


So i have my own class and i want to store an instance of the class by button click into a class array and then use this array in a different form under the same project however despite declaring it as public static i still can't access it on my other form. I have even tried putting it into the class itself just to see if that would work. I have heard you can use a list array but i am not sure how i would do that and again how to access it over my whole project.

Sorry if i missed something obvious or anything I'm fairly new to C#.


Solution

  • Let's say you create the object in Form1 and want to use it in Form2. You can do it like this:

    // Form1-----------------------------------------------------
    
    public partial class Form1 : Form
    {
        public string myName { get; set; }
        public Form1()
        {
            InitializeComponent();
            MyClass myClass = new MyClass() {Name = "John"};
            myName = myClass.Name;
        }
    }
    
    public class MyClass
    {
        public string Name { get; set; }
    }
    
    // Form2-----------------------------------------------------
    
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
            Form1 form1 = new Form1();
            this.label1.Text = form1.myName;
        }
    }