Dynamic properties for classes in visual basic

11,502

Solution 1

It's not possible to modify a class at runtime with new properties1. VB.Net is a static language in the sense that it cannot modify it's defined classes at runtime. You can simulate what you're looking for though with a property bag.

Class Foo
  Private _map as New Dictionary(Of String, Object) 
  Public Sub AddProperty(name as String, value as Object)
    _map(name) = value
  End Sub
  Public Function GetProperty(name as String) as Object
    return _map(name)
  End Function
End Class

It doesn't allow direct access in the form of myFoo.Bar but you can call myFoo.GetProperty("Bar").

1 I believe it may be possible with the profiling APIs but it's likely not what you're looking for.

Solution 2

Came across this wondering the same thing for Visual Basic 2008.

The property bag will do me for now until I can migrate to Visual Basic 2010:

http://blogs.msdn.com/vbteam/archive/2010/01/20/fun-with-dynamic-objects-doug-rothaus.aspx

Share:
11,502
user2912001
Author by

user2912001

Updated on June 04, 2022

Comments

  • user2912001
    user2912001 almost 2 years

    I am a vb.net newbie, so please bear with me. Is it possible to create properties (or attributes) for a class in visual basic (I am using Visual Basic 2005) ? All web searches for metaprogramming led me nowhere. Here is an example to clarify what I mean.

    public class GenericProps
        public sub new()
           ' ???
        end sub
    
        public sub addProp(byval propname as string)
           ' ???
        end sub
    end class
    
    sub main()
      dim gp as GenericProps = New GenericProps()
      gp.addProp("foo")
      gp.foo = "Bar" ' we can assume the type of the property as string for now
      console.writeln("New property = " & gp.foo)
    end sub
    

    So is it possible to define the function addProp ?

    Thanks! Amit

  • Jim H.
    Jim H. about 15 years
    Serializing that could be fun.
  • JaredPar
    JaredPar about 15 years
    @Angry Jim, anytime object is involved, serialization is a risky proposition.
  • user2912001
    user2912001 about 15 years
    @JaredPar - This is good and might work for me. BTW I do not have a hard requirement to use existing class. I am okay with creating the class dynamically. I looked at System.Reflection.Emit yesterday and it was eye opening! --Amit