Objects as Arguments

labisem

Newcomer
Joined
May 20, 2003
Messages
10
I want to pass 2 objects as arguments to a Sub. When I declare the sub:

Public Sub Something (ByRef A As Object, ByRef B As Object)

it gives me an error, because I have Option Strict On. When I make it Off it works, but I know that Option Strict Off it's not a good programming tactic. Is there a way to use Option Strict On and to manage to pass the Objects as parameters to a fuction?
 
Visual Basic:
Sub
Dim Class1 as MyObject = New MyObject("Hello")
Dim Class2 as MyObject = New MyObject("Hello Again")

Something(CType(Class1, Object), CType(Class2, Object))
End Sub

Class MyObject
    Inherits Object
    Private S as String

    Public Sub New(Byval Value as String)
    S = Value
    End Sub

    Public ReadOnly Property MyValue() as String
        Get
            Return S
        End Get
    End Property
End Class

Sub Something(Byref A as Object, Byref B as Object)
Msgbox CType(A, MyObject).MyValue, , "Message from A"
Msgbox CType(B, MyObject).MyValue, , "Message from B"
End Sub
You need to use CType to convert an object into one of it's bases.
CType(Object, ClassToConvertTo)
 
Everything derives from object, therefore there will be no problem with passing anything to an argument that is of that type, whether Option Strict is on or off.

If you got an error, it was probably something else.
 
Thanks a lot! It seems you know VB.NET pretty well. Now, if only you could answer to one more question that I have, I would be gratefull (look "Auto generate instances")
 
Back
Top