Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do VB.NET Optional Parameters work 'Under the hood'? Are they CLS-Compliant?

Tags:

.net

vb.net

clr

cil

Let's say we have the following method declaration:

Public Function MyMethod(ByVal param1 As Integer, _
    Optional ByVal param2 As Integer = 0, _
    Optional ByVal param3 As Integer = 1) As Integer

    Return param1 + param2 + param3
End Function

How does VB.NET make the optional parameters work within the confines of the CLR? Are optional parameters CLS-Compliant?

like image 363
John Rudy Avatar asked Sep 19 '08 17:09

John Rudy


1 Answers

Interestingly, this is the decompiled C# code, obtained via reflector.

public int MyMethod(int param1, 
                   [Optional, DefaultParameterValue(0)] int param2, 
                   [Optional, DefaultParameterValue(1)] int param3)
{
    return ((param1 + param2) + param3);
}

Notice the Optional and DefaultParameterValue attributes. Try putting them in C# methods. You will find that you are still required to pass values to the method. In VB code however, its turned into Default! That being said, I personally have never use Default even in VB code. It feels like a hack. Method overloading does the trick for me.

Default does help though, when dealing with the Excel Interop, which is a pain in the ass to use straight out of the box in C#.

like image 105
MagicKat Avatar answered Nov 15 '22 03:11

MagicKat