Legacy C# with default method arguments

Visual Studio 2010 is officially released. Regardless of its quality, I think that a very large percentage of companies will move from 2008 to 2010 very, very slowly. If you are a software developer “doing” C# in some of this companies, You might find this post useful.

Furthermore, there are more and more nice and useful C# samples to be found, which are in the same time presented using C#4 and VS2010. Most of that “new” code can be re-factored “back” into legacy C#. Currently, I am reluctant to invest in VS2010, so this is my solution for re-factoring C#4 methods using default arguments, back into “legacy” C#.
Consider this method which does not compile in VS2008 (or any other pre-4 C# and pre VS2010 environment).

As we all know, using default values for method parameters, yields nice, simple and logical, code. Like VB.NET can do. Default arguments are a feature of CLR since “day one”. But not the feature of C#, during the last 9+ years (Wow, that is a long time to be using C# ?! ). To do the above using pre-4 C#, one needs to resort to overloads. To match any of the possible variations of the client code, calling the method Copy().

On top of the code above C#4 can use named arguments. Which are outside of the scope of my solution, which I have designed to kind-of-a “implement” default values of method parameters.

Without further obscuring the issues, here is the code of the method Copy(), that is using my solution:

All the code in any of the C# versions can call the method above. All the changes are encapsulated inside the method Copy(),called. The core of the solution is to use the params object [] feature. Plus two of the classes I developed to simplify the usage of params, and thus make the refactoring as simpler as possible.

The whole of the implementation is packaged inside the namespace dbj { }, in the separate assembly. It is used through one interface and one class , implemented in there.

Please note how dbj.Implicitor, takes care of implicit casting to the required type, at runtime. So if caller has done

An exception will be thrown at runtime since internally bool optional arguments were expected, and arguments 1 and “foo” can not be cast to booleans.

My fork of “Fluent Path” by Bertrand Le Roy has this implemented, working, tried, and tested. It resides here: https://hg01.codeplex.com/forks/dbjdbj/fp08 .

Also please see Bertand’s post on how VS2010 actually handles optional arguments, if one wants to compile for .NET 3.5 or older, using VS2010.