Search code examples
vb.netsimplifysimplification

Simplify coding trycast vb.net


Consider I have some models as follow: black, green, blue, red.

I have a function which receive an object and I would like to trycast the object to appropriate model.

Now I have the code like this:

Public Sub SetData(ByVal obj As Object)
    If TryCast(obj, black) IsNot Nothing Then
        Dim m As Black = TryCast(obj, black)
        ......
    ElseIf TryCast(obj, green) IsNot Nothing Then
        Dim m As green = TryCast(obj, green)
        ......
    ElseIf TryCast(obj, blue) IsNot Nothing Then
        Dim m As blue = TryCast(obj, blue)
        ......
    ElseIf TryCast(obj, red) IsNot Nothing Then
        Dim m As red = TryCast(obj, red)
        ......
    Else
        ......
    End If
End Sub

It seems the code is not efficient and consume more memory and use more CPU for its double trycast. How to simplify this code such as checking trycast but get the result model at the same time without double trycast process?


Solution

  • You can use TypeOf so as to know what Class is your object. Example

    If TypeOf obj Is black Then
        Dim m As Black = TryCast(obj, black)
    ElseIf TypeOf obj Is green Then
        Dim m As green = TryCast(obj, green)
    ElseIf TypeOf obj Is blue Then
        Dim m As blue = TryCast(obj, blue)
    ElseIf TypeOf obj Is red Then
        Dim m As red = TryCast(obj, red)
        ......
    Else
        ......
    End If