C#'s 'dynamic' in F#
Asked Answered
O

4

21

One example of using the DLR in C# is as follows:

dynamic dyn = new MyObject();
dyn.MyMethod(); //resolved at runtime

what would be the equivalent in F#?

Thanks.

Offenbach answered 14/11, 2011 at 14:41 Comment(0)
S
25

The ? operator has similar expressive power to the dynamic keyword in C# (but it can be only used for reading of properties, method invocation and setting of properties).

There is no built-in implementation that would allow you to dynamically use properties or methods of a .NET class (via Reflection or DLR), but there are some fairly solid implementations from the community. This has been discussed in another SO question before.

There are also implementations of ? that allow you access some common data sources such as SQL databases. For example, this MSDN article includes a definition that allows you to write db?Query?Foo(1) to call a stored procedure named Foo.

For various other types (such as finding an element in XAML or accessing elements or attributes in XML document), the definition of ? is quite easy to write.

Storage answered 14/11, 2011 at 15:6 Comment(0)
N
9

On the flip side, if you're trying to expose dynamic behavior to C# from F#, you can use DynamicAttribute[MSDN]. For example, declaring a dynamic property might look like

type HasDynamicProperty() =
    [<Dynamic([|true|])>]
    member this.DynamicObject : obj = ...

which is used from C# like

var hdp = new HasDynamicProperty();
dynamic dynObj = hdp.DynamicObject;
Nerti answered 14/11, 2011 at 16:15 Comment(0)
P
9

There's a package called FSharp.Interop.Dynamic and that will make it possible to do a call to a dynamic object using the ? operator.

Pasargadae answered 10/6, 2013 at 7:7 Comment(0)
V
4

F# has the ? operator which you use like so:

 myVariable?SomePropertyThatIsNotDeclared

There is no dynamic keyword equivalent. Take a look at this article for how to use it https://weblogs.asp.net/podwysocki/using-and-abusing-the-f-dynamic-lookup-operator

Vagrant answered 14/11, 2011 at 14:45 Comment(4)
When trying to use ? operator, I get the following error: "error FS0043: Method or object constructor 'op_Dynamic' not found". Any ideas :) ?Offenbach
So, the bottom line is that "?" operator is much more versatile than just "dynamic" keyword. But the downside is that the real functionality should be provided by the user (e.g. if I need to make use of the DLR, I'd have to code all the CallSite<T> stuff manually). Are there any out-of-the-box implementations of "?" in F# libs?Offenbach
Article now returns a 404Bartizan
@Bartizan the link has been replacedVagrant

© 2022 - 2024 — McMap. All rights reserved.