82

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jeroenh
  • 26,362
  • 10
  • 73
  • 104
  • 1
    VB is type safe whether Option Strict on On or Off. Read about the meaning here http://msdn.microsoft.com/en-us/library/hbzz1a9a(VS.80).aspx – John K May 22 '10 at 22:39
  • @jdk ok I guess I'll have to agree. However I meant compile-time checked type safety, as you might have guessed... – jeroenh May 23 '10 at 22:56
  • @jdk: the definition of type safety that everyone uses when talking about programming languages is this one: http://en.wikipedia.org/wiki/Type_safety – Mauricio Scheffer Jul 27 '10 at 01:18
  • @Mauricio: I cringe slightly when Wiki is cited, however in context of the author's question of .NET programming Microsoft's definition that I originally linked to suffices more than enough as they are the creators of the framework and semantics that go with it. – John K Jul 27 '10 at 01:43
  • @jdk: you don't like wikipedia? ok, here are a few more links that say exactly the same, from independent sources: http://stackoverflow.com/questions/260626/what-is-type-safe http://nice.sourceforge.net/safety.html http://lambda-the-ultimate.org/node/1112#comment-12017 http://c2.com/cgi/wiki?StaticTypeSafety – Mauricio Scheffer Jul 27 '10 at 02:03
  • @jdk: Microsoft's definition is about the CLR, not about the languages, which was what the OP was asking about. – Mauricio Scheffer Jul 27 '10 at 02:06
  • @Mauricio, The link applies to Key Security Concepts in the .NET framework, not specifically the CLR. CLR is one part of the framework. See here for more info http://msdn.microsoft.com/en-us/library/ms973842.aspx. There's no need for more generalization when this question is in context of .NET. CTS is important too because it's where language data types meet BCL types... but too long to blog about here :) – John K Jul 27 '10 at 02:16
  • 1
    @jeroenh I was inspired to post a suggestion on Microsoft Connect that it would be nice if VB had something like `dynamic` in C#. Anyone who agrees or disagrees can vote or comment on [Microsoft Connect here](https://connect.microsoft.com/VisualStudio/feedback/details/591963/please-give-vb-net-some-equivalent-for-c-dynamic-with-option-strict-on) – MarkJ Aug 31 '10 at 15:15
  • 3
    The Microsoft VB spec lead has [just blogged about this idea](http://blogs.msdn.com/b/lucian/archive/2010/01/28/core2-dynamic-pseudo-type-scoped-late-binding.aspx). The provisional evaluation from the VB team is "VB has always had its own form late-binding via Object. While it’s a shame that you can’t scope your late-binding smaller than file granularity, this doesn’t seem a big enough problem to justify a second form of late-binding." Dear reader, if you feel strongly about this why not leave a comment on the blog, or on the Microsoft Connect issue mentioned in my earlier comment. – MarkJ Jan 06 '11 at 10:17
  • Duplicate http://stackoverflow.com/questions/3305275/net-4-0-framework-dynamic-features-in-vb-with-option-strict-on – MarkJ Apr 23 '11 at 08:04

8 Answers8

62

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#.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 5
    Except it's not exactly the same. For instance, I couldn't figure out how to dynamically invoke a method (see http://stackoverflow.com/questions/17819977/dynamic-method-calling-in-vb-without-reflection) like you can in C#. – Pat Jul 23 '13 at 20:06
  • 6
    More to the point, the C# model allows you to make an exception for a specific object, the VB model forces you to do it far less granularly – Basic Jul 16 '14 at 21:34
  • I know it's an old question but there is a way to do late binding and keeping Option Strict. From the project properties, Compile tab we can set Late Binding to "None" (and Option Strict take the state "Custom") allowing to do Late Binding in a safer environment than setting it to Off – Sehnsucht Jul 29 '16 at 14:35
  • 1
    You dynamically invoke a method in vb.net on an object by just calling it. Make sure to include parenthesis of course. – Brain2000 May 08 '17 at 20:14
  • CallByName - Should help any web searchers out there: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/early-late-binding/calling-a-property-or-method-using-a-string-name – ryanwebjackson Jan 11 '18 at 18:11
39

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
  • 16
    @Hans Passant: I know that, however C# dynamic is not quite the same as VB's 'late binding'. In C#, with the dynamic keyword I can be very explicit about the dynamic parts of my program. To me it's like telling the compiler: "hey, I know what I'm doing for this specific part of my program". With VB.Net I have to turn off Option Strict for my whole project, which can lead to subtle bugs creeping in because of it. – jeroenh May 23 '10 at 23:02
  • @Hans @jeroen. In your edited code, `app` is inferred as type `Object`, so it's not possible to *use* the Excel Application object `app`. For instance if I substitute `app.Calculate` where you have `REM etc...` it doesn't compile. I think this is the problem jeroen is asking about. The compiler says `Error 1 Option Strict On disallows late binding.` – MarkJ Aug 31 '10 at 12:13
  • @MarkJ - you are absolutely right. I checked the VB.NET version 10 Language Specification to be sure. Shockingly the DLR is not mentioned *anywhere*. Option Strict Off looks completely unavoidable. My apologies for the poor answer. – Hans Passant Aug 31 '10 at 12:43
  • @Hans It's easily overlooked. The MSDN documentation really downplays the necessity of using `Option Strict Off`. Apparently it's possible to write a whole [walkthrough](http://msdn.microsoft.com/en-us/library/ee461504.aspx) without mentioning it, and only mention it briefly in a comment in sample code when [discussing early and late binding](http://msdn.microsoft.com/en-us/library/0tcf61s1.aspx). I think perhaps they are embarassed? – MarkJ Aug 31 '10 at 15:00
  • 1
    I was inspired to post a suggestion on Microsoft Connect that VB should have something like `dynamic`. Anyone who agrees or disagrees strongly can vote or comment on [Microsoft Connect here](https://connect.microsoft.com/VisualStudio/feedback/details/591963/please-give-vb-net-some-equivalent-for-c-dynamic-with-option-strict-on) – MarkJ Aug 31 '10 at 15:16
  • @MarkJ doubt whether this will get through, but it's certainly worth a shot – jeroenh Aug 31 '10 at 16:48
  • The Microsoft VB spec lead has [blogged about this idea](http://blogs.msdn.com/b/lucian/archive/2010/01/28/core2-dynamic-pseudo-type-scoped-late-binding.aspx). The provisional evaluation from the VB team is "VB has always had its own form late-binding via Object. While it’s a shame that you can’t scope your late-binding smaller than file granularity, this doesn’t seem a big enough problem to justify a second form of late-binding." Dear reader, if you feel strongly about this why not leave a comment on the blog, or on the Microsoft Connect issue mentioned in my earlier comment. – MarkJ Jan 06 '11 at 10:20
  • 11
    @jeroenh You can override the project-level options at a file-level with different `Option` directives at the top of the file. – Mark Hurd Aug 19 '12 at 13:58
8

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!! That's what I'm trying to avoid here. 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.

BobRodes
  • 5,990
  • 2
  • 24
  • 26
3

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

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
2

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
goofballLogic
  • 37,883
  • 8
  • 44
  • 62
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vozzie
  • 345
  • 2
  • 9
1

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 .

Wolfgang Grinfeld
  • 870
  • 10
  • 11
0

Yes, ExpandoObject.

Dim DObj = New System.Dynamic.ExpandoObject()

DObj.A = "abc"

DObj.B = 123

Community
  • 1
  • 1
Doron Saar
  • 446
  • 5
  • 7
  • 1
    The ExpandoObject seems to utilize an IDictionary(Of string, object) under the hood. Interesting. – Brain2000 May 08 '17 at 20:16
  • 1
    The question asks for how to do it with `Option Strict On`. Your answer only works with `Option Strict Off` – Nick Jul 21 '17 at 18:58