The back end of my web page has to load a different class depending on a value it receives in the query string. I need a way to make sure that all the other necessary parameters are present so that the class can be instantiated.
Here’s a stripped down example:
Two classes, Car and Cycle both inherit from Vehicle.
Public Class Car
Inherits Vehicle
Private Const _wheels as Int = 4
Private _transmission as string
Private _mpg as int
Public Sub New(Byval transmission as string, Byval mpg as int)
_transmission = transmission
_mpg = mpg
End Sub
End Class
Public Class Cycle
Inherits Vehicle
Private Const _wheels as Int = 2
Private _gears as Int
Public Sub New(ByVal gears as Int)
_gears = gears
End Sub
End Class
This is my query string: ?type=car&transmission=automatic
So I know what the type is, but I haven’t been provided with the mpg details, which I need to be able to instantiate the class.
The “manual” way to do this would be to parse the query string and write something like:
if not string.isNullOrEmpty(transmission) and not string.isNullOrEmpty(mpg) then
dim c as new Car(transmission, mpg)
end if
But this could get messy if there are lots of parameters. It’s also harder to maintain when you want to edit a class object.
I think I want to get the name of each parameter that the class requires, and see if that is present in the query string. However, I would obviously need to do this before instantiating the class. I’m not sure if that’s even possible.
Is this the smart way to do this? Is there a smarter way than just writing out every parameter I need to check the existence of?
The code in this question has been written in vb.net but I’m happy to discuss answers in C#
You can even create the vehicle object dynamically from the query string.