Declare class inside conditional statement?

  • Thread starter Thread starter Andrew
  • Start date Start date
A

Andrew

What's the best way to do this:

Dim bTrue As Boolean
If bTrue = True Then
Dim TheClass As New classA
Else
Dim TheClass As New classB
End If

TheClass.DoSub


The easy way I figured out was, but it doesn't seem as tight as the above
code (and VB.Net doesn't allow the above code):

Dim bTrue As Boolean
If bTrue = True Then
Dim TheClass As New classA
TheStructure.DoSub
Else
Dim TheClass As New classB
TheStructure.DoSub
End If
 
How does the compiler know that DoSub exists on TheClass, if it doesn't know
for sure what type TheClass is?

You have a few options. First you can turn off Option Explicit in that
particular code file and use late binding - that would work.

Or you can declare an interface, IDoSub, and implement it on both classA and
classB (preferred).

Then your code would look something like:

Dim TheClass as IDoSub
Dim bTrue As Boolean

If bTrue = True Then
TheClass = New classA
Else
TheClass = New classB
End If

TheClass.DoSub

-Alex
 
Back
Top