(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”:
- 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).
- 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: