I have a project that has mainly two objects, both inheriting from a base. Like this:
Public Class Vehicle
    Property Model As String
    Property Make As String
End Class
Public Class Truck
    Inherits Vehicle
    Property IsFlatbed As Boolean
End Class
Public Class Car
    Inherits Vehicle
    Property LeatherSeats As Boolean
End Class
Simple enough, eh? Because I don't know if a user will choose car or truck, what I would like to do is just pass around Vehicle.
So, something like this:
Public v As Vehicle
Sub WhichVehicle()
    Select Case cmbVehicle.SelectedItem
        Case Truck
            v = New Truck
        Case Car
            v = New Car
    End Select
    SetFlat (v)
End Sub
This all works, but now I just want to pass v around and use it's properties. Like:
Sub SetFlat (myVehicle As Vehicle)
    myVehicle.IsFlatbed = True
End Sub
The above function doesn't work because myVehicle is a Vehicle, not a Truck.
Is there a way I can pass around a Vehicle type and have the IDE know which type to use? Or am I completely missing a better way to do this?
Basically when you call SetFlat you know your vehicle has a property named IsFlatbed, right?
Then you should declare an interface Flattable which includes this property. The class Truck would implement that interface, and the SetFlat sub would have a Flattable object as a parameter instead of a vehicle.
Edit:
What about this:
Public Interface IFlattable
    Property IsFlatbed() As Boolean
End Interface
Public Class Truck
    Inherits Vehicle
    Implements IFlattable
    Private _isFlatBed as Boolean
    Public Property IsFlatbed() as Boolean Implements IFlattable.IsFlatbed
        Get
            Return _isFlatbed
        End Get
        Set(ByVal value as Boolean)
            _isFlatbed = value
        End Set
End Class
Public v As Vehicle
Sub WhichVehicle()
    Select Case cmbVehicle.SelectedItem
        Case Truck
            v = New Truck
            SetFlat (DirectCast(v, IFlattable))
        Case Car
            v = New Car
    End Select
End Sub
Sub SetFlat (myVehicle As Flattable)
    myVehicle.IsFlatbed = True
End Sub
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With