Tuesday, June 17, 2008

VB.NET Optional parameters

First of all, let me state: I’m not much of a VB fan. However, the company where I’ve worked for about 8 months had everything implemented with VB.NET (for compatibility reasons – they came from a VB6 era) and I had to get used to it. It wasn’t hard, but I definitely prefer other approaches, like C++ or C#.

But there was one little thing that I enjoyed in VB.NET: optional parameters. Take a look at the following example, specially the doSomething method:

(click to enlarge)


The second parameter is optional. That is, if you don’t specify it in a method call, the compiler (remember, the compiler!) inserts the "False" string for you. If we look at the generated IL, we can see that there’s a false string inserted when we call the method with just one parameter. Despite I wrote different calls to the method, the generated call is exactly the same:

(click to enlarge)

Also note that I only wrote one method and, accordingly, only one got generated by the compiler. However, the C# (3.0 and below) compiler doesn’t allow this. To do the same example with C#, we’ll need to write two methods and take advantage of the method overload:

(click to enlarge)

Looking at the generated IL, we’ll see the difference:


(click to enlarge)


Now, the compiler emits the call to different versions of the same method. Of course, two methods were generated. So, why do I like optional parameters?
Well, as you may have noticed, in the C# example I had to wrote two different methods to do the same. And this is the main reason why I think optional parameters are nice. I “googled” a little to find why the C# team decided to keep this feature out, and found a few “pros and cons”:

Pros
  • Using optional parameters will allow programmers to write less code. Less generated methods.
  • It’s intuitive.
  • COM interfaces are filled with default parameters (for example, the Microsoft Office COM automation model - some functions have as many as 30 default parameters). This makes it hard do work with C# (you need to specify all the parameters).

Cons

  • A change in the default parameters will force the user to recompile (imagine if the default parameters change in a server, the client has some troubles).
  • The code generated by the compiler is less obvious (the user didn’t write it).
  • Microsoft tries to limit “the magic” because it’s harder to follow up by programmers.


Optional parameters are not CLS compliant. However, in my opinion, I think it would be good to have them in C#. We had default values in C++, optional parameters exist in VB.NET… We should have them in C#.

I don’t think though that they will ever exist in C#. I’m not seeing it in the near future.

Discussion about this issue:

http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx


Note: The C# 4.0 will allow optional parameters.