Jelle Druyts .NET Consultant
Just another ignorant weirdo from Antwerp, Belgium trying to make sense out of it all
Optional
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
MissSomeParms
.method public instance void MissSomeParms([opt] int32 someInt, [opt] string someString) cil managed { .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:
frmMain_Load
.method private instance void frmMain_Load(object sender, class [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, string) 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.
.param