tags:

views:

104

answers:

3

I recently noticed the CallByName keyword in VB6.

Since this takes a object, procedure name, "call type" and arguments array, can this be used to "fake" some types of polymorphic behavior?

I can make 2 classes, class A and B, each with the same method Foo, and do:

Dim list As New Collection
Dim instanceA As New ClassA
Dim instanceB As New ClassB
Dim current As Object

Call list.Add(instanceA)
Call list.Add(instanceB)

For Each current in list
  Call CallByName(current, "methodName", vbMethod)
Next

Anyone done this before? Problems? Horrible idea or genius idea? Implications? Unintended consequences?

+11  A: 

Why fake polymorphism? VB6 has real polymorphism in the form of interfaces:

' Interface1.cls '

Sub Foo()
End Sub

' --------------------------------------------- '

' Class1.cls '
Implements Interface1

Private Sub Interface1_Foo()
    ? "Hello from class 1"
End Sub

' --------------------------------------------- '

' Class2.cls '
Implements Interface1

Private Sub Interface1_Foo()
    ? "Hello from class 2"
End Sub

' --------------------------------------------- '

' Module1.mod '

Dim x As Interface1
Set x = New Class1
Call x.Foo()
Set x = New Class2
Call x.Foo()
Konrad Rudolph
That I did not know. Have an existing project to work on, and not a single interface in it...had no clue they even existed in this language. Thanks!
Tom Tresansky
+5  A: 

Although I agree with Mr. unicorn, I can't help but point out that CallByName is also unnecessary (in this case) because you can call the method using the standard method syntax and it will result in a late-bound (i.e. not resolved at compile-time) call:

...
For Each current In list
    Call current.methodName
Next

The real use of CallByName is to reference method names/properties where the name comes from a (possibly calculated) string value...an absolute abomination, in my opinion.

Daniel Pratt
Also sounds like a good way to create a sort of VB Injection vulnerability in your code if the string used for CallByName isn't validated properly.
JohnFx
+1  A: 

If you are in a situation where you inherited a huge project with not a single interface in it (it sounds like you did), then CallByName is an awesome tool to fake polymorphism. I use it all the time - never had any issues whatsoever.

AngryHacker
I'm just curious - why not use late-binding instead?
MarkJ
@MarkJ. Slower and more code.
AngryHacker