Optional Parameters (VB.NET)#
In Visual Basic.NET you have the possibility of making method parameters Optional. This means you can omit these parameters when calling the method. However this behavior is not present at runtime and will be simulated when compiled! The compiler just reads the optional parameter’s default value from the called class (which is kept in MSIL metadata) and passes that along when calling the method. This means that if you change the optional value for the function and recompile the called class, nothing will change (except for the MSIL metadata of course). The calling methods will need to be recompiled however, or they will still be using the wrong "optional" parameter!
Public Class frmMain
    Inherits System.Windows.Forms.Form

    Public Sub MissSomeParms(Optional ByVal someInt As Integer = &HABCD, _
        Optional ByVal someString As String = "Hello")

    End Function

    Private Sub frmMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
        Handles MyBase.Load

        MissSomeParms(, "goodbye")
    End Sub
End Class
The MissSomeParms method looks as follows in MSIL:
.method public instance void  MissSomeParms([opt] int32 someInt,
                                            [opt] string someString) cil
  .param [1] = int32(0x0000ABCD)
  .param [2] = "Hello"
  // Code size       1 (0x1)
  .maxstack  8
  IL_0000:  ret
} // end of method frmMain::MissSomeParms

The frmMain_Load method breaks down to:

.method private instance void  frmMain_Load(object sender,
[mscorlib]System.EventArgs e) cil managed
  // Code size       17 (0x11)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4     0xabcd
  IL_0006:  ldstr      "goodbye"
  IL_000b:  callvirt   instance void frmMain::MissSomeParms(int32,
  IL_0010:  ret
} // end of method frmMain::frmMain_Load

You can see that the first default parameter value (0xabcd) has been created in the caller and passed as a regular parameter. The default values are not being recovered by the called function, although they are available in metadata (.param). Obviously, this must be a capability of the compiler, which reads the .param values once and uses them to call the method.

Conclusion: Keep away from Optional Parameters.

Blog | Programming | .NET | Quirks
Comments are closed.
All content © 2015, Jelle Druyts
On this page
Top Picks
Total Posts: 351
This Year: 0
This Month: 0
This Week: 0
Comments: 530
This is my personal website, not my boss', not my mother's, and certainly not the pope's. My personal opinions may be irrelevant, inaccurate, boring or even plain wrong, I'm sorry if that makes you feel uncomfortable. But then again, you don't have to read them, I just hope you'll find something interesting here now and then. I'll certainly do my best. But if you don't like it, go read the pope's blog. I'm sure it's fascinating.

Powered by:
newtelligence dasBlog 2.3.12105.0

Sign In