Right now, I have code that looks something like this:
Private Sub ShowReport(ByVal reportName As String)
Select Case reportName
Case "Security"
Me.ShowSecurityReport()
Case "Configuration"
Me.ShowConfigurationReport()
Case "RoleUsers"
Me.ShowRoleUsersReport()
Case Else
pnlMessage.Visible = True
litMessage.Text = "The report name """ + reportName + """ is invalid."
End Select
End Sub
Is there any way to create code that would use my method naming conventions to simplify things? Here's some pseudocode that describes what I'm looking for:
Private Sub ShowReport(ByVal reportName As String)
Try
Call("Show" + reportName + "Report")
Catch ex As Exception
'method not found
End Try
End Sub
This is C#, should be easy enough to turn it into VB. If you need to pass parameter into the method, they can be added in the 2nd argument to Invoke.
Worked for me in VB .Net MSVS 2015
Python (and IronPython) can do this thing very easily. With .Net though, you need to use reflection.
In C#: http://www.dotnetspider.com/resources/4634-Invoke-me-ods-dynamically-using-reflection.aspx
My quick port to VB.Net:
If i understand the question correctly, you'll have to use Reflection to find the method "show" + reportName and then invoke it indirectly:
Half-baked example:
Insert your own logic there to make up the name for the method to call.
See MSDN documentation of MethodInfo and Assembly for details.
Using reflection:
But I agree with ago, better not change your original code ;-)
You've got a deeper problem. Your strings are too important. Who is passing you strings? can you make them not do that?
Stick with the switch statement, as it decouples your internal implementation (method names) from your external view.
Suppose you localize this to German. You gonna rename all those methods?