2

I have a VB.NET class library project. It has a reference to some legacy library with GuiComponent

 Public Function findById(id As String) As GuiComponent 
        Return session.FindById(id)
 End Function

In a new C# project, I want to call this function and I don't want to reference the whole legacy library for it. So I wrap it with dynamic

((dynamic)sth.findById("someId")).select

Is there a way to return a dynamic type in VB.NET?

Public Function findById(id As String) As Dynamic 'something like this doesn't work
        Return session.FindById(id)
End Function

C# equivalent

 public dynamic findById(string id) {
     return session.FindById(id);
 }

And for sure I don't want to turn off Option Strict for the entire project.

hiichaki
  • 834
  • 9
  • 19
  • 1
    "I don't want to turn off Option Strict for the entire project." - No need to. Create a partial class code file that includes "Option Strict Off" for the code that needs late binding. That is as granular as VB gets for using late-binding. – TnTinMn Feb 04 '21 at 14:50
  • @TnTinMn, I thought `Option Strict Off` can be used in one class only in VB. Is it possible in C#? – hiichaki Feb 04 '21 at 15:08
  • @hiichaki, "Option Strict" is not a class attribute. It is applied on a source file basis and/or project level basis. The source file level setting overrides the project level setting. I originally did not read your question close enough and misunderstood what you are trying to do. Without verifying if it works, a more complex alternative to the solution proposed by Hans would be to define GuiComponent as inheriting from [DynamicObject](https://learn.microsoft.com/en-us/dotnet/api/system.dynamic.dynamicobject?view=netframework-4.8). – TnTinMn Feb 04 '21 at 16:20

1 Answers1

0

No equivalent for dynamic in VB.NET, the return type must be Object. There is no support in the CLR either, but all that is really needed here is to convince the C# compiler that "Object" must be interpreted as "dynamic". In other words, you need to do in VB.NET what the C# compiler does to annotate the return type in the metadata. That merely takes an attribute, like this:

Public Function findById(id As String) As <System.Runtime.CompilerServices.Dynamic> Object
        Return session.FindById(id)
End Function
Hans Passant
  • 922,412
  • 146
  • 1,693
  • 2,536
hiichaki
  • 834
  • 9
  • 19