Can I instantiate an object in Program.cs? If I instantiate the object in a form I have the problem of it being instantiated every time I load that form. Is there another way around that?

My main form has a form load event that currently calls a method that instantiates an object and passes parameters to it. My Windows Forms App has more than one form.

I find whenever I reload the main form the object is instantiated again and I see messageboxes coming from both the objects. I've tried the following line before instantiating the object in the form:

if(myObject == null) 

But I get a redline under "myObject" because it hasn't been instantiated yet. Is there a way for me to instantiate the object in the main form without it being instantiated again whenever I load that form?

Or should I look at instantiating the object in Program.cs instead? How would I do that? Would I be able to use getters and setters to update the object from other parts of the Windows Forms App if I did that?

by privatly via /r/csharp

Leave a Reply