Question

I have such class:

Public Class MyXElement
    Inherits XElement

    Public Sub New(other As XElement)
        MyBase.New(other)
    End Sub

    Public Sub New(name As XName)
        MyBase.New(name)
    End Sub

    Public Sub New(other As XStreamingElement)
        MyBase.New(other)
    End Sub

    Public Sub New(name As XName, content As Object)
        MyBase.New(name, content)
    End Sub

    Public Sub New(name As XName, ParamArray content() As Object)
        MyBase.New(name, content)
    End Sub

End Class

Why does the following code fail?

Dim x1 As XElement = <demo></demo>
Dim x2 As MyXElement
x2 = x1

I get exception: Unable to cast object of type 'System.Xml.Linq.XElement' to type 'MyXElement'.

Was it helpful?

Solution

It's simple - x1 is not MyXElement object! That's the same as trying following:

Dim o1 as Object = new Object()
Dim o2 as String
o2 = o1

The fact that String inherits Object does not mean you can assign Object variable to String

It works the other way. You can easily write following:

Dim x1 As MyXElement = new MyXElement("name")
Dim x2 As XElement
x2 = x1

OTHER TIPS

Marcin explained why it is not working. My answer shows what you need to do to still convert XElement to MyXElement.

You need to use the constructor you defined on MyXElement:

Dim x2 = new MyXElement(x1)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top