<Note: Optional arguments are now available as of C# 2010 /> 

One of the things I missed a lot when I moved to C# is optional arguments. In C++ optional arguments are used a lot. Code as below is a common sight.

void foo(int reqdParam, int optParam = 0)

{

// ...

}

 

foo(5); // gets compiled as foo(5,0)

foo(5, 10);

The reason it is not included in C# is mainly due to versioning problem. Optional arguments are handled in most programming languages by inserting the default value of the optional argument at the call site. So for the above code foo(5) is compiled as foo(5, 0).

The versioning issue comes to play if the call site and the method are in different assemblies. In the next version of the method the default value of optParam may change from 0 to 1 and 0 can become an unsupported value. However the calling code will still contain 0 and hence we may get a run-time issue. The way to get around is re-compiling all the assemblies that contains calls to the method and this simply does not scale.

Another way of handling optional argument would be to automatically generate method overloads based on optional arguments. So the above code on compilation would yield something like

void foo(int reqdParam)

{

foo(reqdParam, 0)

}

void foo(int reqdParam, int optParam)

{

// ...

}

 

foo(5); // calls the first overload

foo(5, 10); // calls the actual function

This is versioning safe. However this is not used by most languages including C#. I do not know why this is not used. This is versioning safe and at the same time gives all the benefits of optional arguments. Side effects would be code-bloat, inclusion of these methods in the call-stack.