Wednesday, October 13, 2004

VJs Tip Of The Day - October 13th 2004

VB.Net InterOp with C# - Optional Parameters

Have you ever wondered about the way VB.Net Optional parameters work with C#... Here is small little exercise to find more... I wrote a simple assembly, with a simple class, with a simple method in VB.Net as follows:

Public Class VBOptionalParamsClass
Public Function OptionalParams(ByVal id As Integer, _
Optional ByVal str As String = "", _
Optional ByVal flag As Boolean = False _
) As Boolean
Return True
End Function
End Class

Then I wrote simple winform exe, with a single button in C#... From here I called the VB.Net assembly as follows:

private void button1_Click(object sender, System.EventArgs e)
{
MyNamespace.VBOptionalParamsClass cls = new MyNamespace.VBOptionalParamsClass();
cls.OptionalParams(1,"something",true);
}

Now the point worth noting here is that all the optional variables in VB.Net became regular variables in C#... I was wondering why couldn't C# compiler create automatic overloads for all those optional variables... Well I do understand that permutation combinations will land up making 16 methods out of 4 optional variables but then there can some way by which only "incremental overloading" {my term} is done... for example in C# I could have

cls.OptionalParams(1)
cls.OptionalParams(1,"something")
cls.OptionalParams(1,"something",true)

I wonder what other implications could be like code repetition in MSIL for all methods or whatever, but then this is just a thought...

With that let us also look at the way MSIL for the method with optional parameters look like... Here we go...

.method public instance bool OptionalParams(int32 id,
[opt] string str,
[opt] bool flag) cil managed
{
.param [2] = ""
.param [3] = bool(false)
... goes on further}

What you can note here is that ther is a [opt] keyword which is thrown into MSIL by the compiler... and also the first lines of the method def contain the default values for the string and boolean parameters which are passed as optional parameters...

That is also one of the reasons why in VB.Net you cannot have Optional parameters without default value...

In anycase while writing your code in VB.Net do make sure that you do not have any Optional values (atleast not in the public interface) as it will not solve its whole big purpose in case your assembly is going to be used by many other apps whose coding language is unknown...


PS: I apologize for not being able to send any tip yesterday... I got caught up in a lengthy discussion with my friend over something more managable and less complicated than software - LIFE... {intentional strong pun was intended!!) just as footer, After more than 2 hours of telphonic conversation I had ended up finding it more unmanagable and more complicated than what I started with... As a result it was better to go to sleep than to think about trivial issues technology... :-)