Advertisements

Coolest function of the day, call an objects method using a variable, Dynamically invoke properties by string name using VB.NET

So I had always wanted to be able to do something like this

dim myDog as new dogobject

dim methodVariable as string = “bark”

myDob.(methodVariable)

i.e. call a method by using a variable

Well, after some serious googling, I finally ran across this function CallByName

http://msdn.microsoft.com/en-us/library/chsc1tx6%28VS.80%29.aspx

this allows me to do this

CallByName(myDog,methodVariable,CallType.Method)

or if you wanted to iterate through ever method in the object you could do

Dim pdc As System.ComponentModel.PropertyDescriptorCollection
pdc = System.ComponentModel.TypeDescriptor.GetProperties(myDog.GetType)

For Each pd As System.ComponentModel.PropertyDescriptor In pdc

CallByName(myDog,pdc.name,CallType.Method)

Next

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: