Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# dynamic object access

Is there a way to access DLR object (eg. DynamicObject subclass instance) members (properties and methods) in F# that is similar to C# dynamic ?

like image 742
Rafael Munitić Avatar asked May 27 '11 09:05

Rafael Munitić


2 Answers

There is a module now on nuget that uses the dlr to implement the dynamic operator. FSharp.Interop.Dynamic

It has several advantages over a lot of the snippets out there.

  • Performance it uses Dynamitey for the dlr call which implements caching and is a PCL library
  • Handles methods that return void, you'll get a binding exception if you don't discard results of those.
  • The dlr handles the case of calling a delegate return by a function automatically, this will also allow you to do the same with an FSharpFunc
  • Adds an !? prefix operator to handle invoking directly dynamic objects and functions you don't have the type at runtime.

    It's open source, Apache license, you can look at the implementation and the basic unit test example cases.

like image 200
jbtule Avatar answered Sep 19 '22 09:09

jbtule


As eriawan mentioned, the ? operator behaves a bit like the dynamic type in C#. The article about calling SQL doesn't rely on anything from the DLR, because you can provide your own implementation of the ? operator and the compiler uses it directly.

I also wrote a brief example of how to use the ? operator to call members using DLR, which is available on F# snippets and there is a more sophisticated version by Matthew Podwysocki. Another snippet shows how to use it to call standard .NET types using Reflection.

See also:

  • Looking for robust, general op_Dynamic implementation
like image 32
Tomas Petricek Avatar answered Sep 20 '22 09:09

Tomas Petricek