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