Friday, April 8, 2011

Dynamic properties for classes in visual basic

Hi,

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

From stackoverflow
  • No - that's not possible. You'd need a Ruby like "method_missing" to handle the unknown .Foo call. I believe C# 4 promises to offer something along these lines.

  • It's not possible to modify a class at runtime with new properties [1]. 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.

    Jim H. : Serializing that could be fun.
    JaredPar : @Angry Jim, anytime object is involved, serialization is a risky proposition.
    Amit : @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
  • 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

0 comments:

Post a Comment