Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Shared Variables in VB6? 2

Status
Not open for further replies.

Ed2020

Programmer
Nov 12, 2001
1,899
GB
Hi,

In the .NET languages I believe it is possible to declare a variable as "Shared" so all instances of the class share the same value in this variable.

Is this possible in VB6?

Ed Metcalfe.

Please do not feed the trolls.....
 
I have never tried this since I never found the need to, but I do not believe you can do this directly.

Depending upon your actual needs, you might try a "backdoor" approach so to speak.

Just a thought, save the variable to your database and query that value.

Goofy, I know but the only thing I can come up with this morning.

One of the really bright guys probably has a more elegant solution (I hope)
 
VB6 doesn't support "Shared" but you can declare a Public variable in a module and it will be visible everywhere in your app ... including instances of a class.

Risky of course because it's also visible in code that's not part of the class where you intend to use it. The other bad thing about this is that your classes are not as portable as they should be because they depend on the existence of a Public variable that must be defined outside the class in order to operate.

Another option is a wrapper class something like this
Code:
Dim mvarShared As Long

Public Property Let Shared(vData As Long)
   mvarShared = vData
End Property

Public Function NewInstance() As TheClass
   Dim NInstance As TheClass
   Set NInstance = New TheClass
   NInstance.Shared = mvarShared
   Set NewInstance = NInstance
   Set NInstance = Nothing
End Function
And "TheClass" would contain
Code:
Private mvarShared As Long

Public Property Let Shared(vData As Long)
   mvarShared = vData
End Property

Public Property Get Shared() As Long
   Shared = mvarShared
End Property

[COLOR=black cyan]' Other Properties, Methods, Etc.[/color]
and you would use it as
Code:
Dim myWrapper                   As New WrapperClass
Dim FirstInstance               As myClass
Dim SecondInstance              As myClass

myWrapper.Shared = 6789
Set FirstInstance = myWrapper.NewInstance
Set SecondInstance = myWrapper.NewInstance
Debug.Print FirstInstance.Shared
Debug.Print SecondInstance.Shared
You can probably clean this up considerably. It's just "speculative" code. I haven't tested it.
 
Thanks Guys.

I thought the answer was probably no, but it's always worth checking. :)

Stars to all of you who suggested something that works though.

Ed Metcalfe.

Please do not feed the trolls.....
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top