Wednesday, May 05, 2004

I received an email about my previous post about optional parameters. The email asked about how you could do this through reflection. Actually pretty easy using the GetType and InvokeMember and you should be all set. The Type.Missing does the trick for passing the optional value. One thing to keep in mind is that if there is no default parameter specified within the function this will cause an exception.

 

Here is a short example:

Code in the form

Imports System

Imports System.Reflection

Public Class Form1

    Inherits System.Windows.Forms.Form

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim o As New InvokeMe

        Dim t As Type

        t = GetType(InvokeMe)

        ' Will throw an error because there is no default value

        't.InvokeMember("PassOptParam", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.InvokeMethod Or BindingFlags.OptionalParamBinding, Nothing, o, New Object() {Type.Missing, Type.Missing})

        t.InvokeMember("PassOptParam", BindingFlags.Public Or BindingFlags.Instance Or BindingFlags.InvokeMethod Or BindingFlags.OptionalParamBinding, Nothing, o, New Object() {10, Type.Missing})

    End Sub

 

Code in the class

Public Class InvokeMe

    Public Function PassOptParam(ByVal Number1 As Integer, Optional ByVal Number2 As Integer = 5) As Integer

        MsgBox(Number2) ' returns 5

    End Function

End Class

 


6:48:42 PM    

I received an email from somebody today asking about the optional keyword. By definition, keyword is used to indicate that a procedure or argument can be omitted when a procedure is called.  Here is a simple example of how you could use it.

 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        PassOptParam(1)

End Sub

 

Private Function PassOptParam(ByVal Number1 As Integer, Optional ByVal Number2 As Integer = 5) As Integer

        MsgBox(Number2) ' returns 5

End Function


5:20:27 PM