Search code examples
vb.netexceptioncasting

Unable to cast object of type 'System.Object' to type (MyClass) Vb.Net


I am using this code to store the object of my class "Device" to Object but I am getting the "system.invalidcastexception" Exception. I cast it in the same way in other classes and there it worked but here it is not working

Public Class Device
Inherits MainDevice

Private TestData As New SortedList(Of Integer, DataVPAA)
Public Sub New(ByVal version As String, ByVal System As String, ByVal IdNumber As UInteger, ByVal Serial As String)
    DataVersion = version
    SystemVersion = System
    Serial_Number = Serial
    IdentNumber = IdNumber

This is where i am getting the Error

    Dim obj As Object
    obj = LoadXml(GetType(Device), Path)
    If obj Is Nothing Then
        ' Some Logic Here
    Else
        Dim dev As New Device
        dev = CType(obj, Device) '**system.invalidcastexception**

        Me.TestData = dev.TestData
        ' Some Logic Here
    End If

End Sub
End Class

Load Function

Function LoadXML(ByVal DeviceType As Type, ByVal Path As String) As Object
Dim obj As New Object
Dim XMLFilePath As String
Dim xmlreader As XmlReader

If Me.GetType = GetType(ABCDevice) Or Me.GetType = GetType(CVDevice) Or Me.GetType = GetType(CV2Device) Then
    XMLFilePath = Path + "\" + strIdentNr + "_" + Serial_Number + ".xml"
Else
    XMLFilePath = Path + "\" + IdentNumber.ToString + "_" + Serial_Number + ".xml"
End If

'Check if File exists
If File.Exists(XMLFilePath) Then
    Dim fs As New FileStream(XMLFilePath, FileMode.Open, FileAccess.Read)
    xmlreader = XmlReader.Create(fs)
    Try 'Try to deserialize to object
        Dim xml_deserializer As New Serialization.XmlSerializer(DeviceType)
        If xml_deserializer.CanDeserialize(xmlreader) Then

            obj = xml_deserializer.Deserialize(xmlreader)

        End If
    Catch ex As Exception
        MessageBox.Show("XML Deserializer Error: " + ex.Message)
    End Try
    fs.Close()
    Return obj
Else : Return Nothing
End If
End Function

I tried to cast it with different methods like directcast and others but i am getting the same exception.


Solution

  • You can make the LoadXml generic and always return the type you want. Such as

    Function LoadXml(Of T)(path As String) As T
        Dim obj As T = Nothing
        Dim XMLFilePath As String
    
        If Me.GetType = GetType(ABCDevice) Or Me.GetType = GetType(CVDevice) Or Me.GetType = GetType(CV2Device) Then
            XMLFilePath = path + "\" + strIdentNr + "_" + Serial_Number + ".xml"
        Else
            XMLFilePath = path + "\" + IdentNumber.ToString + "_" + Serial_Number + ".xml"
        End If
    
        'Check if File exists
        If File.Exists(XMLFilePath) Then
            Using fs As New FileStream(XMLFilePath, FileMode.Open, FileAccess.Read)
                Using reader = XmlReader.Create(fs)
                    Try 'Try to deserialize to object
                        Dim xml_deserializer As New Serialization.XmlSerializer(GetType(T))
                        If xml_deserializer.CanDeserialize(reader) Then
                            obj = xml_deserializer.Deserialize(reader)
                        End If
                    Catch ex As Exception
                        MessageBox.Show("XML Deserializer Error: " + ex.Message)
                    End Try
                End Using
            End Using
        End If
        Return obj
    End Function
    
    Dim dev = LoadXml(Of Device)("path")
    

    Now dev is guaranteed to be a Device. If it's Nothing, it failed