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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can declare the object you want to share as a static field:
…or declare it as a static property:
…and then you access it like this (in other classes):
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():
…and then you access it like this (in Form2):
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:
…and instantiate Form2 like this (in Form1):