Larry Watanabe
Larry Watanabe

Reputation: 10184

Constructing Dynamic Properties at Runtime in VB .NET

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

e.g. 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 property Bar at runtime?

Thanks!

Upvotes: 2

Views: 12613

Answers (4)

Chris McCall
Chris McCall

Reputation: 10397

The answer is Reflection.Emit. Not a lot of fun to code, but does what you want.

Upvotes: 3

JaredPar
JaredPar

Reputation: 755041

Unfortunately there is no way to do alter the structure of a class an runtime. Metadata is fixed at compile time and runs unaltered at runtime.

For the Nitpickers :)

This is not 100% true. The profiling and ENC APIs allow you to change the structure of metadata at runtime. But neither are really applicable for this scenario.

Upvotes: 1

shahkalpesh
shahkalpesh

Reputation: 33474

Adding further to my comment, you can add an indexer to your class - which can let you get/set member variable.

EDIT: I am sorry. I didn't know that vb.net doesn't have indexers.
But one can still write code with backing dictionary, which can work like an indexer

Upvotes: 1

Robert Harvey
Robert Harvey

Reputation: 180858

If you just want 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 particular dictionary item with a method.

Upvotes: 3

Related Questions