GeoLord
GeoLord

Reputation: 3

.net, cast class as a subclass

I need to cast a class as a subclass. Why, because I have a lot of code seems to do this via interop. I want to remove the interop and not update any code. To replace the code that uses MSXML via interop, I want to write a "native" set of code/classes that just uses XmlDocument under the covers and has 100% api spec (for what we are using) so I can delete the interop dll and be 100% in native land. (Sure I guess I pay for references but that should be less than interop cost and I can do memory debugging easier since it's all on the managed heap, right?)

Looking at MSXML6 interop, it seems you can cast an IXMLDOMNode as a IXMLDOMElement. However IXMLDOMElement is defined as:

public interface IXMLDOMElement : IXMLDOMNode

To be specific, I can run this code just fine:

    Dim myXml As FreeThreadedDOMDocument60 = New FreeThreadedDOMDocument60()
    myXml.loadXML("<root><a>1</a><a>2</a></root>")
    Dim oExtPropWideNode As IXMLDOMElement = DirectCast(myXml.selectSingleNode("/root/a"), IXMLDOMElement)
    Console.WriteLine(oExtPropWideNode.text)

Why can I run this? selectSingleNode returns the (base class) IXMLDOMNode and it's getting cast as the (subclass) IXMLDOMElement.

Is this some trickery I need to figure out because it's an ability/usage of interfaces, or sneakiness of the interop level I cannot mimic in native land?

The closest I can get to actually running code is using IConvertible and Convert.ChangeType, but that would require a syntax/code change, which I want to avoid.

Upvotes: 0

Views: 115

Answers (1)

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

IXMDOMNode and IXMLDOMEElement are no classes, but interfaces... the ability to cast between them depends on the class that implements IXMLDOMNode ... does it implement IXMLDOMElement? then you can cast ...

Upvotes: 1

Related Questions