tags:

views:

212

answers:

1
+1  Q: 

Templates In VB

Hi all,

I've got some VB code (actually VBA) which is basically the same except for the type on which it operates. Since I think the DRY principle is a good guiding principle for software development, I want to write one routine for all of the different types which need to be operated on. For example if I had two snippets of code like these:

Dim i as Obj1
Set i = RoutineThatReturnsObj1()
i.property = newvalue

Dim i as Obj2
Set i = RoutineThatReturnsObj2()
i.property = newvalue

I'd like to have something like this to handle both instances:

Sub MyRoutine(o as ObjectType, r as RoutineToInitializeObject, newvalue as value) 
   Dim i as o
   Set i = r
   i.property = newvalue
End Sub

If I were using C++ I'd generate a template and say no more about it. But I'm using VBA. I'm fairly sure there's no capability like C++ templates in the VBA language definition but is there any other means by which I might achieve the same effect? I'm guessing the answer is no but I ask here because maybe there is some feature of VBA that I've missed.

+1  A: 

There's nothing in VB6 that will do that. If you update to Visual Studio Tools for Office with .Net you can use generics:

Function MyRoutine(Of O)(R As Delegate, newvalue As Object) As O
    Dim i As O = CType(r.Method.Invoke(Nothing, Nothing), O)

    'you need another parameter to tell it which property to use'
    ' and then use reflection to set the value'
    i.property = newvalue 
    return i
End Function
Joel Coehoorn