Building Dynamic Properties at Runtime in VB.NET

Is there a way to dynamically create properties at runtime in VB.NET using introspection?

eg. Suppose I had a class

Public Class Foo
   Public Property Bar() As String
       get 
           ...
       end get
      set(ByVal value As String)
          ...
      end set
End Class

      

Is there a way to create a property bar at runtime?

Thank!

+2


source to share


4 answers


Reflection.Emit's answer . Not much fun to code, but does what you want it to.



+3


source


If you need a dynamic list of variables, you can always set up a dictionary object as a member of your class, and then set or get a specific dictionary element using the method.



+3


source


Adding to my comment, you can add a pointer to your class that can allow you to get / set a member variable.

EDIT: I'm sorry. I didn't know vb.net doesn't have indexers.
But it is still possible to write dictionary-backed code that can act as an index

+1


source


Unfortunately, there is no way to change the structure of a class at runtime. Metadata is captured at compile time and executed unchanged at run time.

For Nitpickers :)

This is not 100% true. The profiling API and ENC allow you to modify the metadata structure at runtime. But none of them are applicable for this scenario.

+1


source







All Articles