Reputation: 151
I have multi-form application and I need one instance of MyClass() be accessible from each form. Where should I put it?
Make it public for form1 and then user in other forms Form1.MyClassInstance or what is the best way?
Upvotes: 1
Views: 2260
Reputation: 4975
You can declare the object you want to share as a static field:
public partial class Form1 : Form
{
public static object MyObject;
//...
}
...or declare it as a static property:
public partial class Form1 : Form
{
private static object obj;
public static object MyObject
{
get { return obj; } // read-only
}
//...
}
...and then you access it like this (in other classes):
object obj = Form1.MyObject;
However, if you have multiple instances of Form1, MyObject will be the same for all instances of Form1.
Another approach is setting the Form.Owner property, by calling Form.Show():
public partial class Form1 : Form
{
public object MyObject; // no static required
public Form1()
{
InitializeComponent();
Form2 f2 = new Form2();
f2.Show(this); // this sets the Form.Owner property on f2
}
//...
}
...and then you access it like this (in Form2):
Form1 f1 = (Form1)this.Owner;
object o = f1.MyObject;
The advantage here is that you can now access all public members of Form1, even though they are not declared static. But if you minimize/close Form1, Form2 will also be minimized/closed.
If you don't want to use static or Form.Owner, you can also pass a reference to Form1 instance as a parameter. For example, in Form2 you can write a constructor that takes Form1 as a parameter:
public partial class Form2 : Form
{
public Form2(Form1 f1)
{
InitializeComponent();
object o = f1.MyObject; // access MyObject like this
}
//...
}
...and instantiate Form2 like this (in Form1):
Form2 f2 = new Form2(this);
Upvotes: 1