VB.NET equivalent for C# 'dynamic' with Option Strict On

C#vb.netDynamicOption Strict

C# Problem Overview


Is there an equivalent for the C# 4 'dynamic' keyword when using type safe VB.NET, i.e. with Option Strict On?

C# Solutions


Solution 1 - C#

The equivalent is Object in VB.NET but with Option Strict Off. With Option Strict On there's no equivalent. Put another way the dynamic keyword brings Option Strict Off equivalent functionality to C#.

Solution 2 - C#

VB.NET always had the "dynamic" feature built in, originally called late binding. This syntax was supported forever:

 Dim obj = new SomeComClass()
 obj.DoSomething()

Worked on code implemented in .NET and COM, the latter being the most common use. The dynamic keyword in C# gave it that same capability. It did get changed in VB.NET version 10 however, it is now using the DLR as well. Which adds support for dynamic binding to language implementations like Python and Ruby.

The syntax is exactly the same, use the Dim keyword without As. You will however have to use Option Strict Off, Option Infer On can soften that blow a bit. It does show that C# using a specific keyword to signal dynamic binding was a pretty good move. Afaik all requests to do so in VB.NET as well have as yet been considered but not planned.

If you prefer Option Strict On, then using the Partial Class keyword so you can move some of the code into another source file is probably the most effective approach.

Solution 3 - C#

This will demonstrate what Basic is saying about VB not having the same granularity in this as C#. I have this piece of code in C#, that uses reflection to dynamically invoke a method at runtime:

var listResult = tgtObj.GetType().GetMethod("GetSomeData").Invoke(tgtObj, null);

The reason I'm doing this is that "GetSomeData" could be any of a number of methods, each getting different data. Which method to invoke here is dependent on a string parameter passed into this object at runtime, so, value of "GetSomeData" varies at runtime.

The signature of "GetSomeData" is:

public List<SomeResultSetClass> GetSomeData()

Each one of the methods invoked returns some sort of List<T> object. Next, I'm sending the listResult object to a generic method called Export, which looks like this:

void Export<T>(List<T> exportList, string filePath, byte fileType) where T: class;

Here's where we run into a problem. Invoke returns an object of type System.Object. Of course, a List<T> is also a System.Object, but the interface exposed is the System.Object interface, not the IList interface. If I try to execute the Export method, thus:

myExportObj.Export(listResult, parms.filePath, parms.fileType);

the code fails to compile. The error is:

The type arguments for method '...Export<T>...' cannot be inferred from the usage. Try specifying the type arguments explicitly.

No thanks!! The problem is that the compiler can't find the IList metadata, because it's looking at the System.Object interface. Now, you can create a new List<T>, assign (List<Whatever>) listResult to it, but that defeats the purpose of dynamic invocation in the first place.

The fix is to change var to dynamic:

dynamic listResult = tgtObj.GetType().GetMethod("GetSomeData").Invoke(tgtObj, null);

Since dynamic bypasses static type checking at compile time, we don't get a compile error. Then, when the dynamic object gets passed to the Export method, the DLR (Dynamic Language Runtime) looks to see if it can implicitly cast the object to meet the requirements of the method signature. Which of course it can.

Ok, so that's how things work in C#. With VB, the line goes like this:

Dim listResult = tgtObj.GetType().GetMethod("GetSomeData").Invoke(tgtObj, Nothing)

With Option Strict On, this line upsets the compiler, as expected. With it off, it works fine. In other words, in VB, I have to turn off the type checker for the entire module that contains the line. There is no finer granularity than that.

Solution 4 - C#

You can turn Option Infer On and Option Strict Off and still have something very close.

Solution 5 - C#

There are enough ways to handle methods and properties with late binding COM objects and type safe (Option Strict On). This when using the Microsoft.VisualBasic.Interaction.CallByName and System.Type.InvokeMember methods. (Or create a separate "partial" file where Option Strict is Off).

But to handle events with late binding from VB.NET is not as straightforward as with the dynamic type in C#. You can check the "hack" for that in Dynamic Events in VB.NET.

Solution 6 - C#

The equivalent of the c# dynamic keyword in Vb.Net with option strict on exists as a NuGet package: Dynamitey .

After install-package Dynamitey, one can write Vb.Net code as follows:

Option Strict On : Option Infer On : Option Explicit On
Imports Dynamitey
Module Module1
    Public Sub Main()
        Dim o = Nothing
        o = "1234567890"
        Console.WriteLine(Dynamic.InvokeMember(o, "Substring", 5)) ' writes 67890
    End Sub
End Module

Or the slighly more readable:

Option Strict On : Option Infer On : Option Explicit On
Imports Dynamitey
Module Module1
    <Extension()>
    Public Function Substring(self As Object, offset As Integer) As String
        Return CType(Dynamic.InvokeMember(self, "Substring", offset), String)
    End Function

    Public Sub Main()
        Dim o = Nothing
        o = "1234567890"
        Console.WriteLine(Substring(o, 5)) ' writes 67890
    End Sub
End Module

Tested with VS2017 and .net Framework 4.7.2 .

Solution 7 - C#

Yes, ExpandoObject.

> Dim DObj = New System.Dynamic.ExpandoObject() > > DObj.A = "abc" > > DObj.B = 123

Solution 8 - C#

Note that even with Option Strict on you can still use e.g. an ExpandoObject to access properties like:

Dim doc = JsonConvert.DeserializeObject(Of ExpandoObject)("{""name"":""Bob""}")
Dim lookup as IDictionary(Of String, Object) = doc
lookup("name") ' Bob

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjeroenhView Question on Stackoverflow
Solution 1 - C#Darin DimitrovView Answer on Stackoverflow
Solution 2 - C#Hans PassantView Answer on Stackoverflow
Solution 3 - C#BobRodesView Answer on Stackoverflow
Solution 4 - C#Joel CoehoornView Answer on Stackoverflow
Solution 5 - C#VozzieView Answer on Stackoverflow
Solution 6 - C#Wolfgang GrinfeldView Answer on Stackoverflow
Solution 7 - C#Doron SaarView Answer on Stackoverflow
Solution 8 - C#goofballLogicView Answer on Stackoverflow