Cesar Cesar - 4 months ago 21
Vb.net Question

Can I have same variable definition in different classes in vb.net

Is it possible to have same variable definitions in two different classes.
I just started learning vb.net and I am trying to implement an address validation API, so far the UPS class works for tracking details but the UPSaddress Doesn't. The only different thing between both classes are the path variable and the parameters for the constructors.

Public Class UPS
Private accessKey As String = "0D0F94260Dxxxxx"
Private userName As String = "xxxxxx"
Private passWord As String = "xxxxx"
Private path As String = "https://www.ups.com/ups.app/xml/Track"
Public xml As XmlDocument = New XmlDocument()



public Sub New(trackNo As String)

xml = getUPSXMLbyTrackingNumber(trackNo)
End Sub




Public Function getIdentificationNumber() As String
Dim idNo As String = getNodeValue(xml, "TrackResponse/Shipment/ShipmentIdentificationNumber")

Return idNo.Trim
End Function
End Class


This is the other class.

Public Class UPSAddress

Private accessKey As String = "0D0F94260Dxxxxx"
Private userName As String = "xxxxxxx"
Private passWord As String = "xxxxxxx"
Private path as String = "https://wwwcie.ups.com/ups.app/xml/XAV"
Public xml As XmlDocument = New XmlDocument()

public Sub New(Address As String,City as String,State as String,Zipcode as String)

xml = getUPSXMLAddressValidation(Address,City,State,Zipcode)

End Sub

end class


Is this approach correct? And this is how I call the classes in the VB compiler

Dim trackNo As String = upsTrackNo.Value
Dim Address as String = upsAddress.value
Dim City as String = upsCity.value
Dim State as String = upsState.value
Dim Zipcode as String = upsZipcode.value

'This works'
Dim ups As New UPS(trackNo){
..some code

}

'Im not sure if this will work'
Dim upsAddress as new UPSAddress(Address,City,State,Zipcode){
...some code
}

Answer

Typically you would do this with a base class which holds the common variables. Your other classes then inherit this class and provide their own implementation for the path property:

Public MustInherit Class UPSBase
    Protected accessKey As String = "0D0F94260Dxxxxx"
    Protected userName As String = "xxxxxx"
    Protected passWord As String = "xxxxx"
    Protected MustOverride ReadOnly Property Path As String
End Class

Public Class UPSAddress
    Inherits UPSBase

    Protected Overrides ReadOnly Property Path As String
        Get
            Return "https://wwwcie.ups.com/ups.app/xml/XAV"
        End Get
    End Property
End Class

Public Class UPS
    Inherits UPSBase

    Protected Overrides ReadOnly Property Path As String
        Get
            Return "https://www.ups.com/ups.app/xml/Track"
        End Get
    End Property
End Class