I'm sure this is a simple question, but I don't have enough experience to know the answer. :)
DataClass, Form1, Form2
I have a public class, DataClass
, in a separate file, DataClass.vb
. In DataClass
I have data stored in several arrays that I need to access. I have methods in DataClass
so that I can access the data. One of them is GetName
. Everything works fine on Form1
. I need to access the same data in the arrays on a another form, but I am required to call a new instance of the class, so when I call the methods to access the arrays, the data is empty.
I've seen some threads mention creating a singleton class
, but most are about C# which I am not as familiar with.
What is the best practice?
There are many ways in which you can do this. One of them would involve creating a
Module
and then making the variable that instantiates your classPublic
inside the module:Now, all the forms in your project will be able to access the
DataClass
viaMyGlobalVariables.MyDataClass
.A preferable method would be to add a property to your Form2 that can be set to the
DataClass
instance:Then, you would instantiate your
Form2
as follows (assuming the variable you use to instantiateDataClass
inForm1
is called_dataClass
):And finally, another way would be to override the constructor of
Form2
and allow it to receive a parameter of typeDataClass
. Then, you could instantiateForm2
as:Hope this helps...
You can create a singleton class like this
You can access a single instance through the shared
Instance
member which is initialized automatically. The constructorNew
is private in order to forbid creating a new instance from outside of the class.You can access the singleton like this
But this is not possible
Since the singleton class is accessed through the class name, you can access it from the two forms easily.