Hi,
the following code should work:

1
2
3
4
5
6
7
8
 
#light

let reader = 
  System.Xml.XmlReader.Create
    (new System.IO.StringReader("<doc></doc>"))
let li = ((box reader) :?> System.Xml.IXmlLineInfo)
System.Console.WriteLine(li.LinePosition)

The problem that you probably had is that casting 'reader' directly to 'System.Xml.IXmlLineInfo' using 'reader :?> System.Xml.IXmlLineInfo' doesn't work - I'm not sure if my understanding is correct, but I would say that the :?> operator requires the target type to be inherited from the type of the value on the left side (so having B inherited from A and a instance of (static) type A you could write 'a :?> B'). For dynamic casts to interface types this may be an unnecessary restriction, but I'm not sure if there is any other good reason.

Anyway, the solution is converting the 'reader' to a type obj, which is a base for all .NET types and it is possible to use dynamic cast to any other type from the obj type. Converting any F# value to obj can be done using the 'box' function.

By on 9/12/2007 8:41 AM ()

Hi tomasp,

your solution works great! Thanks for your help.

:?> was among the things I tried without success. Maybe somebody else can shed some light on why the boxing is necessary...

By on 9/12/2007 9:01 AM ()

Stephan,
I'm pretty sure that this is because System.Xml.XmlReader.Create() returns an instance of System.Xml.XmlTextReaderImpl that is upcast to an XmlReader. The problem is that, XmlReader does not implement IXmlLineInfo -- XmlTextReaderImpl does. So, the compiler cannot verify that "reader" actually implements IXmlLineInfo because it is of type XmlReader.

Hopefully, :?> will be fixed soon. Until then, you could define a function that handles the box for you. This should do the trick:

1
2
3
4
5
6
7
8
9
10
11
#light

let dynamic_cast o = (box o) :?> 'a

let reader = 
  System.Xml.XmlReader.Create
    (new System.IO.StringReader("<doc></doc>"))
    
let li: System.Xml.IXmlLineInfo = dynamic_cast reader

System.Console.WriteLine(li.LinePosition)
By on 10/25/2007 5:54 PM ()

Hi all,

I agree this is an unecessary language limitation. Dynamic casts to interfaces should be permitted usig ":?>" without using "box".

We'll fix this.

Thanks

Don

By on 9/12/2007 5:24 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper