Amit
Amit

Reputation: 743

Dynamic properties for classes in visual basic

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

Upvotes: 3

Views: 12712

Answers (3)

JaredPar
JaredPar

Reputation: 755101

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.

Upvotes: 4

WhoIsRich
WhoIsRich

Reputation: 4153

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

Upvotes: 1

Mark Brackett
Mark Brackett

Reputation: 85665

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.

Upvotes: 0

Related Questions