tags:

views:

73

answers:

5

Is there a way to call a procedure in Visual Basic (.net) with a variable name?

For example, the variable strColour can be one of 10 pre-defined values, green blue black white red pink orange yellow indigo purple. How to handle each one is in it's own Sub Routine, colgreen, colblue, colblack and so on.

I can use a bunch of if..then..else and select case, but what I'd like to have is something like VBA Excel's Run "col" & strColour

Is it possible?

A: 

Look into Reflection, it'll let you do what you want. However, in the end, the code will probably be about as complex as your select code.

Aric TenEyck
+3  A: 

it is possible, by using reflection.

Dim thisType As Type = Me.GetType()
Dim theMethod As Reflection.MethodInfo = thisType.GetMethod("col" & strColour, Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)

If Not theMethod Is Nothing Then
    'this, if you have parameters
    theMethod.Invoke(Me, New Object() { add your parameters here, if any })
    'this, if you don't have parameters
    theMethod.Invoke(Me)
End If
Gabriel McAdams
+1  A: 

I would use a select case unless you have a very large number of colours, or even better refactor those methods into 1 method. perhaps a generic one if necessary.

Paul Creasey
+1  A: 

If there is no way to rewrite the color-handling sub-routines, then there is no good way to do it. You options:

  1. Reflection, which allows you to get the names of objects members (methods and properties). If your routines are on an object you can use this.
  2. Believe it or not, it is probably better to have a big select statement! It looks inelegant, but will perform much better than using reflection.
Patrick Karcher
+3  A: 
Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button1.Click
    Dim s As String = "one"
    CallByName(Me, s, CallType.Method) 'Subs must be public

    s = "two"
    CallByName(Me, s, CallType.Method) 'Subs must be public
End Sub

Public Sub one()
    Stop
End Sub

Public Sub two()
    Stop
End Sub
dbasnett
Wow, never knew that that even existed! Still would recommend using a giant Select Case over this or reflection, though.
Chris Haas