2

I'm given to understand that in VB6 user-defined classes cannot have constructors specified. So given a Collection object named entities dimensioned in the main codeblock and a user-defined class named Entity:

Public Class Entry
'local variable(s) to hold property value(s)
Private mvarcurrNameValue As String 'local copy
Private mvarnewwNameValue As String 'local copy

Public Property Let newwNameValue(ByVal vData As String)
    mvarnewwNameValue = vData
End Property

Public Property Get newwNameValue() As String
    newwNameValue = mvarnewwNameValue
End Property

Public Property Let currNameValue(ByVal vData As String)
    mvarcurrNameValue = vData
End Property

Public Property Get currNameValue() As String
    currNameValue = mvarcurrNameValue
End Property
End Class

how do I achieve the following C++/VB.NET idiom in the VB6 realm?

For Each foo In bar
   entities.Add (new Entity("Sinatra","Frank"))     'VB.NET seems to like this but not VB6
Next

I don't know in advance how many Entity instances there will be.

TIA,

Still-learning Steve

user1201168
  • 415
  • 6
  • 19

3 Answers3

4

Try a factory method

Public function NewEntry(a, b) As Entry
   Dim o As Entry
   Set o = New Entry
   o.a = a
   o.b = b
   Set NewEntry = o
End Function

and then

For Each foo In bar 
   entities.Add NewEntry("Sinatra","Frank")
Next 
Community
  • 1
  • 1
MarkJ
  • 30,070
  • 5
  • 68
  • 111
  • 1
    @Deanna thanks for the edit. [You'd think I would know that](http://stackoverflow.com/a/10262247/15639)! :) Obviously don't follow my own advice. – MarkJ May 01 '12 at 11:39
1

To set properties and call methods on an object instance, you need to assign it to a variable first. Once assigned, you can either set the properties directly or use a custom Init() method.

In the Class:

Public Sub Init(ByVal NewName As string, ByVal CurName As String)
  mvarnewwNameValue = NewName
  mvarcurrNameValue = CurName
End Sub

In the loop: Set NewEntry = New Entry NewEntry.Init "weeble", "bob" entities.Add NewEntry

These can either be done directly in your loop or by a factory function as MarkJ said. Note that once it is passed to .Add, you can reuse that variable as long as you set it to a New instance.

Deanna
  • 23,876
  • 7
  • 71
  • 156
1

The other two answers are fine and I've used both approaches. But I figured I put the other simple solution. Here is the vanila VB6 way of doing it:

Dim tempEntity As Entity
For Each foo In bar
   Set tempEntity = New Entity
   tempEntity.currNameValue = "Sinatra"
   tempEntity.newwNameValue = "Frank"
   Call entities.Add(tempEntity) 
   'Or if you prefer the no parens style use this:
   'entities.Add tempEntity
Next foo

A note on naming convention, leading lower-case method/property names are common in Java, but not in .NET or VB6.

tcarvin
  • 10,715
  • 3
  • 31
  • 52