C#: Referencing an instance of a class that was made in another class

82 Views Asked by At

I need some help with C#.

Let's say I have 3 classes. MainMenu, Form1 and Data. I have created an instance of Data (referenced as StoreData) in MainMenu.

public partial class MainMenu : Form
    {
        public Data StoreData = new Data();
    }

I want to be able to access this instance of StoreData in Form1. How do I reference it or import it?

4

There are 4 best solutions below

2
Michał Turczyn On

If you want to reference one class within another class (and don't want to make anything static), composition is one way to go.

You want to reference field of MainForm in Form1, so you want to reference MainForm itself. Thus, you need to create field in Form1 of MainForm type:

public class Form1 : Form
{
    ...
    public MainForm mf { get; set; }
    ...
}

Now, you can access StordeData with mf.StordeData within Form1.

1
TheGeneral On

You can either

  • Make StoreData static in a static class MyAWesomeStatic and call MyAWesomeStatic.StoreData or even in MainMenu class iteself.
  • Pass a reference of StoreData to Form1 either via the constructor or a property when you create it.
  • or pass a reference of MainMenu to form1 and call mainMenu.StoreData when needed.

However, another option might be to use Dependency Injection (DI) and Loosely Couple all this. Have a Singleton instance and pass the in-memory Data Store as some sort of Service (which is what the cool kids might do).

Update

Sorry, still at the beginning stages of learning C#. What does it mean to make a class static?

Given your current level of knowledge and all-things-being-equal, i think the easiest approach might be just pass in a reference

public class Form1
{

    public Data StoreData { get; set; }
}

...

var form = new Form1();
form.StoreData = StoreData;
form.Show();
0
Micheal On

You could make StoreData static in a static class, something like this:

public static class Form1
{ 
    public static Data StoreData { get; set; }
}
1
er-sho On

Suppose your StoreData class have one property

public class StoreData
        {
            public int MyProperty { get; set; } 
        }

Add static property to your mainform.cs and assign value to MyProperty = 1

    public partial class MainMenu : Form
        {
            public static StoreData Data { get; set; }   //static property

            private void MainMenu_Load(object sender, EventArgs e)
            {
                Data = new StoreData { MyProperty = 1 };
            }
        }

And access your StoreData property inside Form1.cs like

public partial class Form1 : Form
    {

        private void Form1_Load(object sender, EventArgs e)
        {
            var id = MainMenu.Data.MyProperty;
        }

    }

Try once may it help you

Result:

enter image description here